How to use OKHTTP to make a post request?

后端 未结 13 1092
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 05:06

I read some examples which are posting jsons to the server.

some one says :

OkHttp is an implementation of the HttpUrlConnection interface p

13条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 05:50

    You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object.

    public JSONObject getJSONFromUrl(String str_url, List params) {      
            String reply_str = null;
            BufferedReader reader = null;
    
            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.
            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 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();
        }
    

提交回复
热议问题