maven依赖

 <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

GET请求:

1、参数直接拼接到URL后面,即http://test.com?a=1&b=2的形式

 /**
* get请求,参数拼接在地址上
* @param url 请求地址加参数
* @return 响应
*/
public String get(String url)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

2、参数放置到一个map中

 /**
* get请求,参数放在map里
* @param url 请求地址
* @param map 参数map
* @return 响应
*/
public String getMap(String url,Map<String,String> map)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get = new HttpGet(builder.build());
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} return null;
}

POST请求:

1、参数放到map中

 /**
* 发送post请求,参数用map接收
* @param url 地址
* @param map 参数
* @return 返回值
*/
public String postMap(String url,Map<String,String> map) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
return null;
}

2、参数是json字符串

 /**
* post请求,参数为json字符串
* @param url 请求地址
* @param jsonString json字符串
* @return 响应
*/
public String postJson(String url,String jsonString)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

entityToString方法:

 private String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null)
{
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048)
{
result = EntityUtils.toString(entity,"UTF-8");
}else {
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}

使用httpClient发送get\post请求的更多相关文章

  1. HttpClient发送get post请求和数据解析

    最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传 ...

  2. 使用HttpClient发送Get/Post请求 你get了吗?

    HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议 ...

  3. 在ASP.NET Core中用HttpClient(三)——发送HTTP PATCH请求

    在前面的两篇文章中,我们讨论了很多关于使用HttpClient进行CRUD操作的基础知识.如果你已经读过它们,你就知道如何使用HttpClient从API中获取数据,并使用HttpClient发送PO ...

  4. 使用httpclient发送get或post请求

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

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

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

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

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

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

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

  8. httpclient 发送一个请求

    httpclient版本 4.1 发送一个post请求 public static JSONObject post(String url,JSONObject json){ HttpClient cl ...

  9. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

随机推荐

  1. windows下虚拟环境安装方法

    方法一:使用virtualenv安装虚拟环境 1.安装virtualenv pip install virtualenv 2.随意创建文件夹(将来虚拟环境会在这个文件夹)    mkdir mypro ...

  2. [Eclipse]--Error:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path.

    一段时间没用eclipse后,再去打开以前的项目,发现一打开前线标红.查看错误的时候,如下图所示: Error:The superclass "javax.servlet.http.Http ...

  3. 检测密码 Exercise06_18

    import java.util.Scanner; /** * @author 冰樱梦 * 时间:2018年下半年 * 题目:检测密码 * */ public class Exercise06_18 ...

  4. STL之vector4

    描述 将一个n行m列矩阵元素输入存储后并输出. 部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码. int main() { vector< vector<int> > ...

  5. linux的打包与解压

    zip: 打包 :zip something.zip something (目录请加 -r 参数) 解包:unzip something 指定路径:-d 参数 创建加密 zip 包 使用 -e 参数可 ...

  6. ios 如何获得系统时间和日期

    iphone 如何获得系统时间和日期 代码如下: #import <time.h> 1.获得当前的系统时间和日期 //获得系统时间 NSDate *  senddate=[NSDate d ...

  7. mysql group_concat函数

    函数语法: group_concat( [DISTINCT] 要连接的字段 [Order BY 排序字段 ASC/DESC] [Separator '分隔符'] ) 下面举例说明: select * ...

  8. 全文检索引擎[asp版]

    search.asp: <% set DM=server.CreateObject("DeepMap.HLL")pnn=0: wdd="": pnn=Re ...

  9. Solr的精确匹配搜索

    情景: 利用Solr做一批词的逆文档频率.Solr中存储的每条数据为一篇文章,此时需要查出某词在多少篇文章中出现过,然后用公式:某词逆文档频率 = 总文章数 / (出现过某词的文章数+1) 来计算. ...

  10. [TypeScript] Infer the Return Type of a Generic Function Type Parameter

    When working with conditionals types, within the “extends” expression, we can use the “infer” keywor ...