Maven 的 pom 引入:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
依赖的 jar 文件:
GET 方法:
import org.apache.http.HttpEntity;
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public static String get(String url) throws Exception{
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpGet);
try {
response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK
HttpEntity entity2 = response2.getEntity();
String response=EntityUtils.toString(entity2,"utf-8");//返回报文
EntityUtils.consume(entity2);//关闭资源
return response;
} finally {
response2.close();//关闭资源
}
}
POST 方法访问 http:
import org.apache.http.HttpEntity;
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public static String post(String url,String json) throws Exception{
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);//设置消息头 Content-Type application/json; charset=UTF-8
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
CloseableHttpResponse response2 = HttpClients.createDefault().execute(httpPost);
try {
response2.getStatusLine().getStatusCode();//HttpStatus.SC_OK
HttpEntity entity2 = response2.getEntity();
String response=EntityUtils.toString(entity2,"utf-8");//返回报文
EntityUtils.consume(entity2);//关闭资源
return response;
} finally {
response2.close();//关闭资源
}
}
POST 方法访问 https:
去除 ssl 验证
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于