HttpClient模拟get,post请求并发送请求参数(json等)
import java.io.IOException; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; /**
*
*/
public class HttpClientUtil { public static void main(String arg[]) throws Exception {
String url = "test.com";
JSONObject params = new JSONObject();
params.put("SRC_STM_CODE", "wsf");
params.put("TENANT_ID", "123");
params.put("NM", "张三");
params.put("BRTH_DT", "1983-01-20");
params.put("GND_CODE", "1");
JSONArray params2 = new JSONArray();
JSONObject param3 = new JSONObject();
param3.put("DOC_TP_CODE", "10100");
param3.put("DOC_NBR", "100200198301202210");
param3.put("DOC_CUST_NM", "test");
params2.add(param3);
params.put("DOCS", params2);
String ret = doPost(url, params).toString();
System.out.println(ret);
} /**
httpClient的get请求方式2
* @return
* @throws Exception
*/
public static String doGet(String url, String charset)
throws Exception {
/*
* 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。
* 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get
* 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。
*/
/* 1 生成 HttpClinet 对象并设置参数 */
HttpClient httpClient = new HttpClient();
// 设置 Http 连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/* 2 生成 GetMethod 对象并设置参数 */
GetMethod getMethod = new GetMethod(url);
// 设置 get 请求超时为 5 秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/* 3 执行 HTTP GET 请求 */
try {
int statusCode = httpClient.executeMethod(getMethod);
/* 4 判断访问的状态码 */
if (statusCode != HttpStatus.SC_OK) {
System.err.println("请求出错: "+ getMethod.getStatusLine());
}
/* 5 处理 HTTP 响应内容 */
// HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
for (Header h : headers)
System.out.println(h.getName() + "------------ " + h.getValue());
// 读取 HTTP 响应内容,这里简单打印网页内容
byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
response = new String(responseBody, charset);
System.out.println("----------response:" + response);
// 读取为 InputStream,在网页内容数据量大时候推荐使用
// InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
System.out.println("发生网络异常!");
e.printStackTrace();
} finally {
/* 6 .释放连接 */
getMethod.releaseConnection();
}
return response;
} /**
* post请求
* @param url
* @param json
* @return
*/ public static JSONObject doPost(String url,JSONObject json){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
} }
HttpClient模拟get,post请求并发送请求参数(json等)的更多相关文章
- Android入门:用HttpClient模拟HTTP的GET和POST请求
一.HttpClient介绍 HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器: Android已经集成了HttpClient,因此可以直接使用: ...
- 用HttpClient模拟HTTP的GET和POST请求(转)
本文转自:http://blog.csdn.net/xiazdong/article/details/7724349 一.HttpClient介绍 HttpClient是用来模拟HTTP请求的,其 ...
- .Net HttpClient 模拟登录微信公众平台发送消息
1.模拟登录 public WeiXinRetInfo ExecLogin(string name, string pass) { CookieContainer cc = new CookieCon ...
- 20200726_java爬虫_使用HttpClient模拟浏览器发送请求
浏览器获取数据: 打开浏览器 ==> 输入网址 ==> 回车查询 ==> 返回结果 ==> 浏览器显示结果数据 HttpClient获取数据: 创建HttpClient ==& ...
- HttpClient模拟http请求
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- JAVA发送HttpClient请求及接收请求结果
1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...
- 使用HttpClient发送请求接收响应
1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...
- HTTPClient模拟Get和Post请求
一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...
- 使用HttpClient发送请求、接收响应
使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象. CloseableHttpClient httpclient = HttpClients.c ...
随机推荐
- Jmeter(四)-断言/检查点
断言就类似LoadRunner中的检查点.对上一个请求返回的信息,做字符串.数据包大小.HTML.XML.图片等做判断,确保返回的信息的准确性. 添加响应断言:欢迎您 如果登陆页登陆成功,则后台会返回 ...
- line-height属性详解
line-height属性详解:http://www.cnblogs.com/dolphinX/p/3236686.html
- hdu 5945 Fxx and game(单调队列优化DP)
题目链接:hdu 5945 Fxx and game 题意: 让你从x走到1的位置,问你最小的步数,给你两种走的方式,1.如果k整除x,那么你可以从x走一步到k.2.你可以从x走到j,j+t<= ...
- hdu 2829 Lawrence(斜率优化DP)
题目链接:hdu 2829 Lawrence 题意: 在一条直线型的铁路上,每个站点有各自的权重num[i],每一段铁路(边)的权重(题目上说是战略价值什么的好像)是能经过这条边的所有站点的乘积之和. ...
- redis cluster中添加删除重分配节点例子
redis cluster配置好,并运行一段时间后,我们想添加节点,或者删除节点,该怎么办呢. 一,redis cluster命令行 //集群(cluster) CLUSTER INFO 打 ...
- spring mvc 实现文件上传下载
/** * 文件上传 * @param pictureFile */ @RequestMapping("/reportupload") public ResponseInfo up ...
- kubernetes port nodePort targetPort 理解
port The port that the service is exposed on the service's cluster ip (virsual ip). Port is the serv ...
- MinGW32 +QT4.8.6+QT Creator+CMAKE的安装
参考网址: http://www.360doc.com/content/15/0813/09/7256015_491331699.shtml http://m.fx114.net/qa-196-213 ...
- 如何阅读一本书([美] 莫提默·J. 艾德勒 / 查尔斯·范多伦 )
进入豆瓣读书 前言 2017年1月2日跟着熊猫书院开始了为期十月的阅读计划. 熊猫书院是一个微信公众号,但仅对熊猫书院学员开放.它是一个很好的读书产品,从入学申请.入学报到.班长 ...
- 顺序栈和链式栈(C++实现)
顺序栈,是一种基于数组的存储表示. 实现类代码如下: template<class T> class SeqStack{ T *element; int top; int maxSize; ...