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. FZU 2027 单词问题 map标记字符串典型问题

    题目链接:单词问题 找一个字符串里的所有单词,重复的只输出一次.关于map函数key值是字符串的问题一直比较含糊... 挣扎了一番,大概是,map的key值是char型数组的时候,标记的是地址,于是有 ...

  2. 使用ContentObserve监听用户发出的短信

    import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.app.Activit ...

  3. Topcoder SRM 584 DIV1 600

    思路太繁琐了 ,实在不想解释了 代码: #include<iostream> #include<cstdio> #include<string> #include& ...

  4. 6.1.2Linux下Socket编程

    tcp简单实验 server.c #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include ...

  5. FZU 2082 过路费

    树链剖分模板题 #include <cstdio> #include <iostream> #include <cstring> #include <algo ...

  6. powershell玩转litedb数据库

    powershell可以玩nosql数据库吗?答案是肯定的.只要这个数据库兼容.net,就可以很容易地被powershell使用. 发文初衷:世界上几乎没有讲powershell调用nosql的帖子, ...

  7. shell指令expr和test指令

    通过expr指令可以进行+.-.*.\.%等运算,但是有一点值得注意,使用乘法时,要在*前加上一个\符号. 通过test指令可以进行逻辑测试,进行测试的情况有四种: 1.整数测试 a.判断两个整数是否 ...

  8. iOS图片攻略之:有3x自动生成2x 1x图片

       关键字:Xcode插件,生成图片资源 代码类库:其他(Others) GitHub链接:https://github.com/rickytan/RTImageAssets   本项目是一个 Xc ...

  9. 在Windows平台搭建PHP开发环境(四)

    一.概念 1.1 在Windows下搭建 wamp: apache(iis) + php + mysql +phpmyadmin 1.2 在Linux下搭建     lamp: linux + php ...

  10. leetcode 229 Majority Element II

    这题用到的基本算法是Boyer–Moore majority vote algorithm wiki里有示例代码 1 import java.util.*; 2 public class Majori ...