1

Ok I ma having problem with understanding okhttp. all I need is to upload an image to server.

enter image description here

this image is screenshot from my android studio , it seems I cannot import org.apache.http.NameValuePair; what is alternative container then ?

and as you noticed .open(url) is also red it is saying cannot resolve java.net.url

this is my full code:

public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {
    String reply_str = null;
    BufferedReader reader = null;
    final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",image_str));
    nameValuePairs.add(new BasicNameValuePair("caption",caption));
    nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
    try {
        URL url = new URL(str_url);
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection con = client.open(url);
        con.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(getEncodedParams(params));
        writer.flush();
        StringBuilder sb = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reply_str = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    // try parse the string to a JSON object. There are better ways to parse data.
    JSONObject jObj;
    try {
        jObj = new JSONObject(reply_str);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
}

//in this case it's NameValuePair, but you can use any container
public String getEncodedParams(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();
    for (NameValuePair nvp : params) {
        String key = nvp.getName();
        String param_value = nvp.getValue();
        String value = null;
        try {
            value = URLEncoder.encode(param_value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (sb.length() > 0) {
            sb.append("&");
        }
        sb.append(key + "=" + value);
    }
    return sb.toString();
}
Moudiz
  • 7,211
  • 22
  • 78
  • 156

2 Answers2

3

instead of BasicNameValuePair you can use a Pair

the equivalent for getKey() would be pair.first. The one for getValue() would be pair.second

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
2

Suggest that you refer to the following for the alternative of NameValuePair:

    ...
            OkHttpClient client = new OkHttpClient();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("key1", "value1");
                jsonObject.put("key2", "value2");
                jsonObject.put("key3", "value3");
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                Request request = new Request.Builder()
                        .url("http://...")
                        .post(body)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        // do something...
                    }
                    @Override
                    public void onResponse(Response response) throws IOException {
                        // do something...
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

Hope this helps!

BNK
  • 23,994
  • 8
  • 77
  • 87
  • Yes, just for some small testing projects :) – BNK Oct 11 '15 at 13:18
  • 1
    oh thats good man good luck and thank you for helping me. I work android in my part time alone and its annoying bcz I work in database(oracle) but I am trying to improve my self with androids when I have free time – Moudiz Oct 11 '15 at 13:33
  • hi man can you please help me in this http://stackoverflow.com/questions/33089581/what-is-the-reasong-of-this-error-java-io-ioexception-content-length-and-stream? there probelm in the execution – Moudiz Oct 12 '15 at 22:37