1.get
package com.me.modules.httpclient.get;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DemoHTTPGet02 {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient=null;
HttpGet httpGet=null;
HttpEntity responseEntity=null;
CloseableHttpResponse response=null;
try {
httpClient = HttpClients.createDefault();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("Userid","47"));
URI url = new URIBuilder().setScheme("http").setHost("127.0.0.1:8080/weavernorth9/demojsp/a.jsp").setPort(8080).setParameters(params).build();
httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
responseEntity = response.getEntity();
System.out.println("响应数据-->"+responseEntity);
String HtmlResult = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("响应数据html形式-->"+HtmlResult);
System.out.println(JSON.parseObject(HtmlResult).getString("code"));
}else{
System.out.println("请求地址是"+httpGet.getURI()+"响应状态码是"+response.getStatusLine().getStatusCode());
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (response!=null){
response.close();
}
if (httpClient!=null){
httpClient.close();
}
}
}
}
2.post
package com.me.modules.httpclient.post;
import com.alibaba.fastjson.JSON;
import com.me.modules.excel.easyexcel.Student;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class DemoHTTPPost02 {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient=null;
HttpPost httpPost=null;
HttpEntity responseEntity=null;
CloseableHttpResponse response=null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://www.bilibili.com/");
Student student = new Student();
student.setName("xiaochu");
String jsonString = JSON.toJSONString(student);
StringEntity httpEntity =new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
responseEntity = response.getEntity();
System.out.println("响应数据-->"+responseEntity);
String HtmlResult = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("响应数据html形式-->"+HtmlResult);
System.out.println(JSON.parseObject(HtmlResult).getString("code"));
}else{
System.out.println("请求地址是"+httpPost.getURI()+"响应状态码是"+response.getStatusLine().getStatusCode());
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
}
3.常用工具类
package com.util.clj.httputil;
import com.alibaba.nacos.client.config.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
static {
connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(MAX_TIMEOUT);
configBuilder.setSocketTimeout(MAX_TIMEOUT);
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
connMgr.setValidateAfterInactivity(5000);
requestConfig = configBuilder.build();
}
public String doGet(String url) {
return doGet(url, new HashMap<>());
}
public String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
HttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpGet httpPost = new HttpGet(apiUrl);
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("执行状态码 : " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inStream = entity.getContent();
result = IOUtils.toString(inStream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<>());
}
public String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, String.valueOf(Charset.forName("UTF-8"))));
response = httpClient.execute(httpPost);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
public String doPost(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}