Java发送HTTP请求访问接口:
HttpClient 是apache 组织下面的一个用于处理HTTP 请求和响应的开源工具
1、HTTP-REQUEST-GET
/**
* HTTP-REQUEST-GET
* @param url
* @param dataMap
* @return
*/
public static String sendGetHttpRequest(String url, Map<String, String> dataMap){
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String param = "";
String content = "";
try {
httpClient = HttpClients.createDefault();
if(null != dataMap && !CollectionUtils.isEmpty(dataMap.keySet())){
StringBuffer bufParam = new StringBuffer();
for (String key : dataMap.keySet()) {
bufParam.append(key+"=").append(dataMap.get(key)).append("&");
}
param = bufParam.subSequence(0, bufParam.length()-1).toString();
StringBuffer urlParam = new StringBuffer();
urlParam.append(url).append("?").append(param);
url = urlParam.toString();
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
httpResponse.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return content;
}
2、HTTP-REQUEST-POST
/**
* HTTP-REQUEST-POST
* @param url
* @param dataMap:传参
* @return
*/
public static String sendPostHttpRequest(String url, Map<String, String> dataMap){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (String key : dataMap.keySet()) {
formparams.add(new BasicNameValuePair(key, dataMap.get(key)));
}
CloseableHttpResponse httpResponse = null;
String content = "";
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
httpResponse.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
3、HTTP-REQUEST-UPLOAD(参数是个文件)
/**
* 上传文件
*
*/
private static void upload(String url, File file, Map<String, Object> dataMap) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
httpPost.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
httpPost.setHeader("Connection", "keep-alive");
FileBody fileBody = new FileBody(file);
String data = JSON.toJSONString(dataMap);
StringBody stringBody1 = new StringBody(data, ContentType.MULTIPART_FORM_DATA);
try {
HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("filename", fileBody).addPart("data", stringBody1).setCharset(CharsetUtils.get("UTF-8"))
.build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
HttpResponse httpResponse;
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
JSONObject result = JSONObject.parseObject(content);
if (result == null ) {
throw new Exception("上传文件失败,返回数据为:" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
注释:1、Accept-Language 是HTTP 请求里面的一个属性,用于告诉服务器浏览器可以支持什么语言。如果网站支持多语种的话,可以使用这个信息来决定返回什么语言的网页 。zh-CN 是表示中文,fr-FR 是表示法语
2、请求头Accept-Charset 是告诉服务器,客户端提交的表单使用的编码。与服务器的响应内容编码无关。而响应头Content-Type 中的 charset则将告诉浏览器,服务器返回的文本采用什么编码
Connection:keep-alive长连接,需要服务端支持。同时Keep-Alive不会永久保持连接,它有一个保持时间,可以在不同的服务器软件(如Apache)中设定这个时间
4、发送HTTP请求并携带Cookie
/**
* HTTP-REQUEST-GET
* @param url
* @param dataMap
* @param cookie 身份认证
* @return
*/
public static String sendGetHttpRequest(String url, Map<String, String> dataMap, String cookie) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String param = "";
String content = "";
try {
httpClient = HttpClients.createDefault();
if(null != dataMap && !CollectionUtils.isEmpty(dataMap.keySet())){
StringBuffer bufParam = new StringBuffer();
for (String key : dataMap.keySet()) {
bufParam.append(key+"=").append(dataMap.get(key)).append("&");
}
param = bufParam.subSequence(0, bufParam.length()-1).toString();
StringBuffer urlParam = new StringBuffer();
urlParam.append(url).append("?").append(param);
url = urlParam.toString();
}
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", cookie);
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
content = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
} catch (Exception e) {
throw new BizException(null,"HTTP GET请求发生异常",e);
} finally{
try {
httpResponse.close();
httpClient.close();
} catch (Exception e) {
throw new BizException(null,"资源释放发生异常",e);
}
}
return content;
}
MAVEN依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcomponents-client</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>