发送get 请求(方式一)
public static void doGet(String url){
//1.获取httpclient
CloseableHttpClient httpClient = HttpClients.createDefault();
//接口返回结果
CloseableHttpResponse response = null;
try {
//1.创建get请求
HttpGet httpGet = new HttpGet(url);
//2.设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);
/*此处可以添加一些请求头信息,例如:
httpGet.addHeader("content-type","text/xml");*/
//3.提交参数
response = httpClient.execute(httpGet);
//4.得到响应信息
int statusCode = response.getStatusLine().getStatusCode();
//5.判断响应信息是否正确
if(HttpStatus.SC_OK != statusCode){
//终止并抛出异常
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//8.关闭所有资源连接
if(null != response){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
发送get 请求(方式二)
public static JSONObject sendGet(String url) throws IOException, URISyntaxException {
JSONObject httpresponse = null;
CloseableHttpClient client = HttpClients.createDefault();
URIBuilder uri = new URIBuilder(url);
HttpGet get = new HttpGet(uri.build());
//get.addHeader("access_token", accessToken);
CloseableHttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
httpresponse = JSONObject.parseObject(EntityUtils.toString(entity, "utf-8"));
response.close();
client.close();
return httpresponse;
}
发送post请求(参数以表单方式提交)
public static JSONObject doPost(String url, Map<String,Object> content)
{
CloseableHttpClient client = HttpClients.createDefault();
HttpPost request =new HttpPost();
JSONObject httpresponse = null;
try{
request.setURI(new URI(url));
List<NameValuePair> list =new ArrayList<NameValuePair>();
if(MapUtils.isNotEmpty(content))
{
for(Map.Entry<String,Object> entry:content.entrySet())
{
list.add(new BasicNameValuePair(entry.getKey(),(String)entry.getValue()));
}
}
request.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
request.setHeader("Content-Type","application/x-www-form-urlencoded");
HttpResponse response =client.execute(request);
// 返回json格式
String result = EntityUtils.toString(response.getEntity());
httpresponse = JSONObject.parseObject(result);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return httpresponse;
}
发送Post请求(参数以JSON方式提交)
创建JSONObject参数实体:
JSONObject jsonParam = new JSONObject();
jsonParam.put(key,value);
public static JSONObject sendPost(JSONObject json,String url) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
//post.addHeader("token", "A9NN4VcSys-Y4cUsIReQj-sCCzpMjwP_jLvT");
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
// 返回json格式
String result = EntityUtils.toString(httpResponse.getEntity());
response = JSONObject.parseObject(result);
} catch (Exception e) {
log.error("请求异常:"+e.getMessage());
throw new RuntimeException(e);
}
return response;
}
以上方法用到的包,可自行来这里cv
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.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.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;