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

        由于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包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值