- HttpGet
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
1.创建HttpClient对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
2.创建请求方法的实例,并指定请求URL。创建HttpGet对象;
HttpGet httpGet = new HttpGet("要请求的url");
- GET 请求不存在请求实体部分,键值对参数放置在 URL 尾部,因此请求头不需要设置 Content-Type 字段
- 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse对象。
clientRespone=httpClient.execute(httpGet);
- 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
if (clientRespone != null && clientRespone.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(clientRespone.getEntity(), "utf-8");
}
- 释放连接。无论执行方法是否成功,都必须释放连接
if (clientRespone != null) {
try {
clientRespone.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- HttpPost
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject
import org.apache.http.util.EntityUtils;
import java.io.IOException;
1.创建HttpClient对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
2.创建HttpPost对象。
HttpPost httpPost = new HttpPost(url);
3.设置请求头
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("",);//根据实际需要设置
4.设置请求参数。
JSONObject params = new org.json.JSONObject();
params.put("key",val);
params.put("key",val);
// 构建消息实体
StringEntity entity = new StringEntity(params.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
httpPost.setEntity(entity);
5.执行post请求
clientRespone=httpClient.execute(httpPost);
- 判断是否请求成功,成功则获取服务器的响应内容
if (clientRespone != null && clientRespone.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(clientRespone.getEntity(), "utf-8");
System.out.println(clientRespone.getStatusLine().getStatusCode());
}
8.释放链接,关闭资源
if (clientRespone != null) {
try {
clientRespone.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
上面是我自己写的拷出来的比较简单,
下面这链接比较详细,也比较全面可以参考(我觉得是不错的)
https://www.jianshu.com/p/9504ecc7abad