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");
        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解码一下

猜你喜欢

转载自www.cnblogs.com/dxk1019/p/9187763.html