Http Post 请求发送 Json数据

    public static String httpPostWithJSON(String url, String json) throws Exception {
        // 将JSON进行UTF-8编码,以便传输中文
        String encoderJson = URLEncoder.encode(json, "UTF-8");

        HttpClient httpclient = new HttpClient();
        PostMethod method = new PostMethod(url);
        RequestEntity requestEntity = new StringRequestEntity(encoderJson);
        method.setRequestEntity(requestEntity);
        method.addRequestHeader("Content-Type", "application/json;charset=uft-8");
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");//乱码问题
int result = httpclient.executeMethod(method); String response = method.getResponseBodyAsString(); method.releaseConnection(); return response; }

 

接口获取拿到需要解码

        InputStream in = req.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
        StringBuffer sb = new StringBuffer();
        String tempStr = "";
        while ((tempStr = reader.readLine()) != null) {
            sb.append(tempStr);
        }
        System.out.println(URLDecoder.decode(sb.toString()));   //获取的Json解码一下

 

posted @ 2018-06-15 16:05  糖里里  阅读(1592)  评论(0编辑  收藏  举报