http请求测试实例(采用json-lib解析)
编程技术  /  houtizong 发布于 3年前   80
由于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包
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接