这篇随笔记录了 HttpClient 的 GET 和 POST 请求
使用 maven 构建依赖包, 我使用的版本是 4.5.3
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.5.3</version>
- </dependency>
代码如下:
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- public class HttpRequest {
- private static final String USER_AGENT = "Mozilla/5.0";
- private static final String TOKEN = "Bearer adad2342dfbcdcb44232bf6a";
- private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
- // 发送 GET 请求
- public static String sendGet(String url){
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(url);
- httpGet.addHeader("User-Agent", USER_AGENT);
- httpGet.addHeader("Authorization", TOKEN);
- try{
- HttpResponse response = httpClient.execute(httpGet);
- HttpEntity entity = response.getEntity();
- result = EntityUtils.toString(entity);
- }catch (Exception e){
- e.printStackTrace();
- }
- return result;
- }
- // 发送 POST 请求
- public static String sendPost(String url,Map<String,String> mapParam){
- String result = "";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(url);
- httpPost.setHeader("Content-Type",CONTENT_TYPE);
- httpPost.addHeader("User-Agent" ,USER_AGENT);
- httpPost.addHeader("Authorization", TOKEN);
- try{
- if (mapParam != null){
- List<NameValuePair> postData = new ArrayList<NameValuePair>();
- for (Map.Entry<String,String> entry : mapParam.entrySet()){
- postData.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
- }
- httpPost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
- }
- HttpResponse response = httpClient.execute(httpPost);
- HttpEntity entity = response.getEntity();
- result = EntityUtils.toString(entity);
- }catch (Exception e){
- e.printStackTrace();
- }
- return result;
- }
- }
来源: http://www.bubuko.com/infodetail-2503293.html