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

本文介绍了三种使用不同库通过 HTTP POST 方法发送 JSON 数据的方式:利用 HttpURLConnection、HttpClient 和 OkHttp 发送 JSON 数据到服务器,并获取响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值