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包

你可能感兴趣的:(java,web开发)