HttpURLConnection 、HttpPost、Okhttp 等POST方式发送JSON数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010886975/article/details/78742388

一、HttpURLConnection Post方式发送JSON数据

    public class GetResult extends AsyncTask<String, String, String> {
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... arg0) {
            String result = "";
            URL url = null;
            BufferedReader reader = null;
            try {
                String parma = "{\"name\": \"hah\"}";
                url = new URL("url");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Length", String.valueOf(parma.length()));
                connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
                connection.setRequestProperty("accept","application/json");

                OutputStream out = connection.getOutputStream();
                out.write(parma.getBytes());
                out.flush();
                out.close();

                if (connection.getResponseCode()==200){

                    reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));
                    result = reader.readLine();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return result;
        }

        @Override
        protected void onPostExecute(String re) {
            super.onPostExecute(re);
            value.setText(re);

        }

    }

2、HttpPost 发送json数据

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("url");
                StringEntity se = new StringEntity("{\"dog\":{\"name\": \"hah\"}}");
                httpPost.setEntity(se);
                httpPost.setHeader("Content-Type", "application/json");
                @SuppressWarnings("deprecation")
                HttpResponse httpResponse = httpClient.execute(httpPost);

                String str = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);

                re = JSON.parseObject(str,ModelArrayResult.class);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

3、Okhttp post 发送JSON

public class HttpUtil {

    public static final OkHttpClient client = new OkHttpClient();
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    public static <T> T post(String Url, String postBody, Class<T> clazz) {
        T result = null;
        Request request = new Request.Builder()
                .url(Url)
                .post(RequestBody.create(MEDIA_TYPE_JSON,postBody))
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
//            此处response.body().string()能用调用一次!
            String str = response.body().string();
            Log.i("ResponseToString",str);
            result = JSON.parseObject(str, clazz);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/u010886975/article/details/78742388
今日推荐