当前位置:首页 > 开发 > 编程语言 > Json > 正文

http请求测试实例(采用json-lib解析)

发表于: 2015-06-07   作者:bijian1013   来源:转载   浏览:
摘要:         由于fastjson只支持JDK1.5版本,因些对于JDK1.4的项目,可以采用json-lib来解析JSON数据。如下是http请求的另外一种写法,仅供参考。 package com; import java.util.HashMap; import java.util.Map; import

        由于fastjson只支持JDK1.5版本,因些对于JDK1.4的项目,可以采用json-lib来解析JSON数据。如下是http请求的另外一种写法,仅供参考。

package com;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

public class BJTTest {

    public static void main(String[] args) {

        Map paramMap = new HashMap();
        paramMap.put("queryName", "张三");
        paramMap.put("age", "30");

        JSONObject jsonObj = new JSONObject(paramMap);
        String jsonStr = jsonObj.toString();
        System.out.println("jsonStr:" + jsonStr);

        try {
            PostMethod postMethod = new PostMethod("http://serviceAddress/system//address/queryInfo");
            StringRequestEntity se = new StringRequestEntity(jsonStr, "application/json", "utf-8");
            postMethod.setRequestEntity(se);

            HttpClient httpClient = getHttpClient();
            httpClient.executeMethod(postMethod);

            String body = new String(postMethod.getResponseBody(), "UTF-8");
            JSONObject jsonObject = new JSONObject(body);

            System.out.println("result:" + jsonObject.toString());
        } catch (Exception e) {
            System.out.println("调用异常:" + e.getMessage());
        }
    }

    private static HttpClient getHttpClient() {
        HttpConnectionManagerParams http_pams = new HttpConnectionManagerParams();
        http_pams.setConnectionTimeout(10000);
        http_pams.setSoTimeout(10000);
        http_pams.setDefaultMaxConnectionsPerHost(10);
        http_pams.setMaxTotalConnections(10);

        MultiThreadedHttpConnectionManager http_manger = new MultiThreadedHttpConnectionManager();
        http_manger.setParams(http_pams);
        HttpClient httpClient = new HttpClient(http_manger);

        return httpClient;
    }
}

 

附:依赖JAR包

http请求测试实例(采用json-lib解析)

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号