httpclient 发送一个请求
public static JSONObject post(String url,JSONObject json){
HttpClient 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");
post.setEntity(s); HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
模拟提交form:
private static HttpPost postForm(String url, Map<String, String> params){ HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>(); Set<String> keySet = params.keySet();
for(String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
} try {
log.info("set utf-8 form entity to httppost");
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} return httpost;
}
get请求
public static String get(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
String body = null; log.info("create httppost:" + url);
HttpGet get = new HttpGet(url);
body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body;
}
发起一个post请求,设置超时:
需要注意各个版本设置超时的api都不相同。
还有需要注意的是3中超时:
1,连接超时:connectionTimeout 指的是连接一个url的连接等待时间。
3,SocketTimeout :定义了Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
public static String sendPostRequest(String url, String str, String contentType, String charset){
// HttpParams httpParams = new BasicHttpParams();//4.1版本
// HttpConnectionParams.setConnectionTimeout(httpParams, 5000);//建立连接超时时间,防止调用url为死链,消耗服务器io
// HttpConnectionParams.setSoTimeout(httpParams, 3000);// 响应超时
// CloseableHttpClient httpClient = new DefaultHttpClient();
RequestConfig.Builder requestBuilder = RequestConfig.custom();//4.3.5版本
requestBuilder = requestBuilder.setConnectTimeout(5000);
//requestBuilder = requestBuilder.setConnectionRequestTimeout(100); HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
CloseableHttpClient httpClient = builder.build(); HttpPost post = new HttpPost(url);
//RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
//post.setConfig(requestConfig);
post.setHeader("Content-Type", contentType);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = null;
try {
post.setEntity(new StringEntity(str, charset));
long start = System.currentTimeMillis();
try {
response = httpClient.execute(post,responseHandler);
} catch (Exception ConnectionTimeoutException) {//建立连接超时异常
long p = System.currentTimeMillis() - start;
log.error("sendPostRequest has a ConnectionTimeoutException timeout=> "+ p +" "+ url);
}finally{
//httpClient.getConnectionManager().shutdown();
post.releaseConnection();
}
} catch (Exception e) {
log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
}
return response;
}
httpclient 发送一个请求的更多相关文章
- 【JAVA】通过HttpClient发送HTTP请求的方法
HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...
- Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- (一)----使用HttpClient发送HTTP请求(通过get方法获取数据)
(一)----使用HttpClient发送HTTP请求(通过get方法获取数据) 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是 ...
- .net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包
前言: 通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddl ...
- Httpclient发送json请求
一.Httpclient发送json请求 public String RequestJsonPost(String url){ String strresponse = null; try ...
- 网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求
一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是 ...
- (三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 一.GET和POST的对比: 在漫长的时间当中,其他的方法逐渐的退出了历史舞台,最常用的只剩下GE ...
- springboot2.X集成HttpClient 发送HTTPS 请求
1)jar <!--httpclient 发送外部https/http 请求--> <dependency> <groupId>org.apache.httpcom ...
随机推荐
- NetworkComms网络通信框架V3结构图
NetworkComms网络通信框架序言 来自英国的c#网络通信框架,历时五年打造,由英国剑桥的2位工程师倾情开发,最新版本V3.x版本.
- Writing an Hadoop MapReduce Program in Python
In this tutorial I will describe how to write a simpleMapReduce program for Hadoop in thePython prog ...
- 6.1.1Linux下Socket编程
什么是Socket Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序.要学Internet上的TCP/IP网络编程, ...
- Hibernate 的配置文件
Hibernate 配置文件 •Hibernate 配置文件主要用于配置数据库连接和 Hibernate 运行时所需的各种属性 •每个 Hibernate 配置文件对应一个 Configuration ...
- poj 1742 Coins (动态规划,背包问题)
Coins Time Limit: 3000MS Memory Limit: 30000K Total Submissions: 32977 Accepted: 11208 Descripti ...
- 在Tomcat下配置Solr 4.x 版本
solr是一款非常优秀的全文检索服务器,最新版本在配置和前台页面上都做了较大的改动, 所以对用惯了老版本的朋友们来说,再重新配置新版本的solr,无疑又是一件痛苦的事情. 配置环境:windows ...
- DOM 之 SAX操作
SAX采用部分读取的方式,可以进行大型文件的处理,而且只需要从文件中读取特定的内容,SAX解析可以由用户自己建立对象模型.
- 解决json跨域时错误:SyntaxError: invalid label
将数据做以下返回: $callback = $_GET['callback']; echo $callback.'('.json_encode(array('html'=>$html)).')' ...
- BCP 导入导出数据库数据
使用 bcp 将数据库迁移到 Azure SQL Database --所有 都是在本机sql上运行--先开启cmdshellEXEC sp_configure 'show advanced opti ...
- fragment的一些bug
自从Android3.0引入了Fragment之后,使用Activity去嵌套一些Fragment的做法也变得更加流行,这确实是 Fragment带来的一些优点,比如说:Fragment可以使你能够将 ...