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

来源:互联网 发布:正交矩阵的性质证明 编辑:程序博客网 时间:2024/06/07 01:30

一、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;    }}
原创粉丝点击