Json格式的http请求

时间:2023-03-09 00:36:46
Json格式的http请求
服务端PHP代码可以从这里下载:https://github.com/lornajane/PHP-Web-Services

1.使用volley实现:

request要用JsonObjectRequest,这个request在url后面带有一个JSONObject类型的参数

如果服务端有检测http头的请求数据类型和接受数据类型(比如有的服务端会根据http头中的Accept字段标示的类型,返回json,xml或其他数据类型,也会根据Content-type字段的标示,按json或form类型解析请求参数),还需要在getHeaders回调中设置头部参数,如果服务端不检测,可以不设置:

 headers.put("Accept", "application/json");//表示接受json类型的响应
 headers.put("Content-Type", "application/json; charset=UTF-8");//表示传递给服务器的参数是json类型

String strUrl = "http://10.2.152.133/test/rest/rest.php/items";
try {
    JSONObject jsonBody = new JSONObject("{\"name\":\"Brett\",\"link\":\"haha\"}");

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
            strUrl, jsonBody, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("qf", response.toString());
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("qf", error.getMessage());
                }
            }

    ) {
        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json; charset=UTF-8");

            return headers;
        }
    };

    MyApp.mRequestQueue.add(request);
} catch (Exception e) {
    e.printStackTrace();
}

2.使用httputils实现:

content-type设置也要根据情况需要,同volley一样

普通的表单请求是addQueryStringParameter(get)或addBodyParameter(post),json请求是setBodyEntity

protected void postJsonByXutils() {
    String strUrl = "http://10.2.152.133/test/rest/rest.php/items";
    RequestParams requestParams = new RequestParams();
    requestParams.addHeader("Content-Type", "applicasettion/json");

    JSONObject json = new JSONObject();

    try {
        json.put("name", "zy");
        json.put("link", "zy2");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    requestParams.setBodyEntity(new StringEntity(json.toString(), "utf-8"));

    MyApp.mHttpUtils.send(HttpRequest.HttpMethod.POST,
            strUrl,requestParams,new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String strResult = responseInfo.result;
                    Log.d("qf", strResult);
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.d("qf", msg);
                }
            });
}

3.使用httpurlconnection:

    protected void postJsonByHttpURLConnection() {
        HttpURLConnection httpcon;
        String url = "http://10.2.152.133/test/rest/rest.php/items";
        String data = "{\"name\":\"Brett2\",\"link\":\"haha2\"}";
        String result = null;
        try {
//Connect
            httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
            httpcon.setDoOutput(true);
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.setRequestProperty("Accept", "application/json");
            httpcon.setRequestMethod("POST");
            httpcon.connect();

//Write
            OutputStream os = httpcon.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(data);
            writer.close();
            os.close();

//Read
            BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));

            String line = null;
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            br.close();
            result = sb.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//http://blog.csdn.net/lamp_zy/article/details/52300629
    }//特别注意一点,在进行接口调用时,会发生乱码 connection.setRequestProperty("ContentType", "utf-8"); // 设置发送数据的格式   connection.setRequestProperty("Accept-Charset", "utf-8");