这篇随笔记录了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,MapmapParam){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 postData = new ArrayList ();47 for (Map.Entry 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 }