httpclient版本 4.1
发送一个post请求
    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的连接等待时间。

2,读取数据超时:soTimeout  指的是连接上一个url,获取response的返回等待时间

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 发送一个请求的更多相关文章

  1. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  2. Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  3. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  4. (一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    (一)----使用HttpClient发送HTTP请求(通过get方法获取数据) 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是 ...

  5. .net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包

    前言:  通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddl ...

  6. Httpclient发送json请求

    一.Httpclient发送json请求 public String RequestJsonPost(String url){    String strresponse = null;    try ...

  7. 网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求

    一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是 ...

  8. (三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 一.GET和POST的对比: 在漫长的时间当中,其他的方法逐渐的退出了历史舞台,最常用的只剩下GE ...

  9. springboot2.X集成HttpClient 发送HTTPS 请求

    1)jar <!--httpclient 发送外部https/http 请求--> <dependency> <groupId>org.apache.httpcom ...

随机推荐

  1. C#图书资源【更新中...】喜欢的就转存吧

    百度分享暂时取消了,需要的朋友可以直接关注我,我发给你. 重点篇 1.C#与.NET3.5高级程序设计 2.C#与.NET3.5高级程序设计.rar 3.Effective_C#_中文版_改善C#程序 ...

  2. 二分图 最大权匹配 km算法

    这个算法的本质还是不断的找增广路: KM算法的正确性基于以下定理:若由二分图中所有满足A[i]+B[j]=w[i,j]的边(i,j)构成的子图(称做相等子图)有完备匹配,那么这个完备匹配就是二分图的最 ...

  3. netbios wins dns LLMNR

    NetBIOS名称 Network Basic Input/Output System  (RFC-1001,1002)网络基本输入/输出系统协议 NetBIOS是一种高级网络接口,最初是在硬件中实 ...

  4. java 面向对象编程 第20章 XML技术解析

    1.  XML:extended Markup Language  可扩展标记语言,利用标签和子标签方式描述数据. 2.  声明<?xml version=”1.0”?>版本号 注释< ...

  5. YouTube技术架构

    谈不上翻译,就是摘录 1 billion video views per day 1.Apache 2.Python 3.Linux (SuSe) 4.MySQL 5.psyco, a dynamic ...

  6. sql 如何过滤重复记录

    distinct : select distinct ID from table1

  7. Achieving High Availability and Scalability - ARR and NLB

    Achieving High Availability and Scalability: Microsoft Application Request Routing (ARR) for IIS 7.0 ...

  8. SQLite实现Top功能

    SQlite本身没有top功能,无法向TSQL一样下Select top 100 * from tb_table,但SQLite提供了一个Limit关键字用来取得相应行数的资料 具体语法实例:Sele ...

  9. Program D--贪心-区间覆盖

    Given several segments of line (int the X axis) with coordinates [Li,Ri]. You are to choose the mini ...

  10. jQuery dialog 简介

    dialog是jQuery UI 库的一个UI组件,所以使用dialog时,不仅要引入jQuery.js(因为它只是轻量级的基础框架),还需要引入jQueryUI的js及相关css文件 示例: < ...