Java学习之HttpClient的GET与POST请求

Posted 乌鸦也能展翅高飞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习之HttpClient的GET与POST请求相关的知识,希望对你有一定的参考价值。

这篇随笔记录了HttpClient的GET和POST请求

使用maven构建依赖包,我使用的版本是4.5.3

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

代码如下:

 1 import org.apache.http.HttpEntity;
 2 import org.apache.http.HttpResponse;
 3 import org.apache.http.NameValuePair;
 4 import org.apache.http.client.entity.UrlEncodedFormEntity;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.client.methods.HttpPost;
 7 import org.apache.http.impl.client.CloseableHttpClient;
 8 import org.apache.http.impl.client.HttpClients;
 9 import org.apache.http.message.BasicNameValuePair;
10 import org.apache.http.protocol.HTTP;
11 import org.apache.http.util.EntityUtils;
12 
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Map;
16 
17 public class HttpRequest {
18     private static final String USER_AGENT = "Mozilla/5.0";
19     private static final String TOKEN = "Bearer adad2342dfbcdcb44232bf6a";
20     private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
//发送GET请求
21 public static String sendGet(String url){ 22 String result = ""; 23 CloseableHttpClient httpClient = HttpClients.createDefault(); 24 HttpGet httpGet = new HttpGet(url); 25 httpGet.addHeader("User-Agent", USER_AGENT); 26 httpGet.addHeader("Authorization", TOKEN); 27 try{ 28 HttpResponse response = httpClient.execute(httpGet); 29 HttpEntity entity = response.getEntity(); 30 result = EntityUtils.toString(entity); 31 }catch (Exception e){ 32 e.printStackTrace(); 33 } 34 return result; 35 } 36 //发送POST请求 37 public static String sendPost(String url,Map<String,String> mapParam){ 38 String result = ""; 39 CloseableHttpClient httpClient = HttpClients.createDefault(); 40 HttpPost httpPost = new HttpPost(url); 41 httpPost.setHeader("Content-Type",CONTENT_TYPE); 42 httpPost.addHeader("User-Agent" ,USER_AGENT); 43 httpPost.addHeader("Authorization", TOKEN); 44 try{ 45 if (mapParam != null){ 46 List<NameValuePair> postData = new ArrayList<NameValuePair>(); 47 for (Map.Entry<String,String> entry : mapParam.entrySet()){ 48 postData.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); 49 } 50 httpPost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8)); 51 } 52 HttpResponse response = httpClient.execute(httpPost); 53 HttpEntity entity = response.getEntity(); 54 result = EntityUtils.toString(entity); 55 }catch (Exception e){ 56 e.printStackTrace(); 57 } 58 return result; 59 } 60 }

 






以上是关于Java学习之HttpClient的GET与POST请求的主要内容,如果未能解决你的问题,请参考以下文章

爬虫概念与编程学习之如何爬取视频网站页面(用HttpClient)

纪念一下java学习之第一个get请求。

pygame学习之绘制移动的矩形

java学习之内省

Java学习之IO流四

学习之http协议