HttpURLConnection与HttpClient是java目前较为常用的访问HTTP的api接口的方法。
自己将这两种方法整理为demo,在此保存。
package com.Util.connection;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
*访问进行api
*/
public class Connection {
/**
* 使用HttpClient的Get方式访问api
* 获得返回信息
* @param url
* @return
*/
public String getResponseByHttpClientByGet(String url){
String response = "";//存储返回信息
CloseableHttpClient httpClient = null;//HttpClient实例
HttpGet httpGet ;//Get方式提交
CloseableHttpResponse httpResponse = null;//创建接收返回信息对象
try {
httpClient = HttpClientBuilder.create().build();//创建HttpClient实例
httpGet = new HttpGet(url);//Get方式提交
httpResponse= httpClient.execute(httpGet);//接收返回信息对象
if (httpResponse.getStatusLine().getStatusCode()==200){//验证状态码
HttpEntity entity = httpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
response = EntityUtils.toString(entity,"utf-8");//存储返回信息
}else {
throw new Exception("接收状态码异常");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally { //关闭连接
try {
if (httpClient != null){
httpClient.close();
}
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
/**
*使用HttpClient的Post方式访问api
* 获得返回信息
* @param url
* @param params
* @return
*/
public static String getResponseByHttpClientByPost(String url , List params){
String response = "";//存储返回信息
CloseableHttpClient httpClient = null;//HttpClient对象
HttpPost httpPost ;//POST请求:
CloseableHttpResponse httpResponse = null;//存储返回信息对象
UrlEncodedFormEntity urlEncodEntity ;
try {
httpClient = HttpClientBuilder.create().build();//创建HttpClient实例
httpPost = new HttpPost(url);//POST请求实例
urlEncodEntity = new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(urlEncodEntity);//将参数保存到HttpPost
httpResponse = httpClient.execute(httpPost);//创建返回信息实例
if (httpResponse.getStatusLine().getStatusCode()==200){//取出服务器返回的状态码,等于200就说明请求和响应成功
HttpEntity entity = httpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
response = EntityUtils.toString(entity,"utf-8");//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {//关闭连接
if (httpClient != null){
httpClient.close();
}
if (httpResponse != null){
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
/**
* 使用HttpURLConnection的Post方式访问api
* @param serverUrl
* @return
*/
public static String getResponseByHttpURLConnectionByPost(String serverUrl){
URL url = null;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
url = new URL(serverUrl);//获取访问地址URL
connection = (HttpURLConnection) url.openConnection();// 2. 创建HttpURLConnection对象
/* 设置请求参数等 */
connection.setRequestMethod("POST");// 请求方式 // 超时时间
connection.setConnectTimeout(3000);
connection.setDoOutput(true);// 设置是否输出
connection.setDoInput(true); // 设置是否读入
connection.setUseCaches(false); // 设置是否使用缓存
connection.setInstanceFollowRedirects(true); // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置使用标准编码格式编码参数的名-值对
connection.connect();// 连接
// 从连接中读取响应信息
int code = connection.getResponseCode();
String msg = "";
if (code == 200) {
reader = new BufferedReader( new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
msg += line + "\n";
}
reader.close();
}
// 5. 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader.toString();
}
/**
* 使用HttpURLConnection的Get方式访问api
* @param serverUrl
* @return
*/
public static String getResponseByHttpURLConnectionByGet(String serverUrl){
URL url = null;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
url = new URL(serverUrl);//获取访问地址URL
connection = (HttpURLConnection) url.openConnection();// 2. 创建HttpURLConnection对象
/* 设置请求参数等 */
connection.setRequestMethod("GET");// 请求方式 // 超时时间
connection.setConnectTimeout(3000);
connection.setDoOutput(false);// 设置是否输出
connection.setDoInput(true); // 设置是否读入
connection.setUseCaches(true); // 设置是否使用缓存
connection.setInstanceFollowRedirects(true); // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.connect();// 连接
// 从连接中读取响应信息
int code = connection.getResponseCode();
String msg = "";
if (code == 200) {
reader = new BufferedReader( new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
msg += line + "\n";
}
reader.close();
}
// 5. 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader.toString();
}
}
注:
ConnectionRequest类与ConnectionResponse类是对应参数的实体类,我的Demo里所有的参数是通过Map的方式直接传参,未用到该实体类,这样大部分的api访问都可使用该demo的方法去访问。
package com.Util.connection;
import java.util.Map;
/**
*工具
*/
public class ConnectionUtil {
//将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子
public static String urlencode(Map data) {
StringBuffer sb = new StringBuffer();
int j= 1;
for (Map.Entry i : data.entrySet()) {
sb.append(i.getKey()).append("=").append(i.getValue());
if (j == data.size()) return sb.toString();
sb.append("&");
j++;
}
return sb.toString();
}
}
package com.Util.connection;
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.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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) throws IOException {
//接口地址
String requestUrl = "http://route.showapi.com/60-27";
//params用于存储要请求的参数
Map params = new LinkedHashMap();
params.put("origin","120.173513,30.182344");
params.put("destination","120.17971,30.187726");
params.put("size","3");
params.put("key","30bfe2cb061e2abb25fc2af3fab04227");
//调用httpRequest方法,这个方法主要用于请求地址,并加上请求参数
String urlInfo = "https://restapi.amap.com/v4/direction/truck";
String url = "https://restapi.amap.com/v4/direction/truck?"+Connect.urlencode(params);
//String url = "https://restapi.amap.com/v4/direction/truck?origin=120.173513,30.182344&destination=120.17971,30.187726&size=3&key=30bfe2cb061e2abb25fc2af3fab04227";
//String result =Connect.getResponse(url);
//System.out.println(result);
String response = Connect.getResponseByHttpClient_Post(url);
//String response = Connect.getResponseByHttpClient_Get(url);
System.out.println(response);
}
}
class Array{
int i;
String var;
private List step;
public List getStep() {
return step;
}
public void setStep(List step) {
this.step = step;
}
}
class Connect{
//将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子
public static String urlencode(Map data) {
StringBuffer sb = new StringBuffer();
int j= 1;
for (Map.Entry i : data.entrySet()) {
sb.append(i.getKey()).append("=").append(i.getValue());
if (j == data.size()) return sb.toString();
sb.append("&");
j++;
}
return sb.toString();
}
public static String connectURL(String dest_url, String commString) {
String rec_string = "";
URL url = null;
HttpURLConnection urlconn = null;
OutputStream out = null;
BufferedReader rd = null;
try {
url = new URL(dest_url);
//HttpURLConnection对象不能直接构造,需要通过URL类中的openConnection()方法来获得。
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setReadTimeout(1000 * 30); // 设置超时时间
urlconn.setRequestMethod("POST");// 设置请求方式
urlconn.setDoInput(true);// 设置是否从httpUrlConnection读入
urlconn.setDoOutput(true);// 设置是否向HttpURLConnection输出
out = urlconn.getOutputStream();// 添加 附加数据,只有POST方式才可以添加,所以,使用此方法后,会自动把方法设置为POST
out.write(commString.getBytes("UTF-8"));
out.flush();
out.close();
rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream(),"UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1)
sb.append((char) ch);
rec_string = sb.toString();
} catch (Exception e) {
return "";
} finally {
try {
if (out != null) {
out.close();
}
if (urlconn != null) {
urlconn.disconnect();
}
if (rd != null) {
rd.close();
}
} catch (Exception ignored) {
}
}
return rec_string;
}
//连接及解析高德地图
public static String getResponse(String serverUrl){
//用JAVA发起http请求,并返回json格式的结果
StringBuffer result = new StringBuffer();
try {
//建立连接
URL url = new URL(serverUrl);
URLConnection conn = url.openConnection();
//调用api,并返回流
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
//循环输出流获取流内信息
String line;
while((line = in.readLine()) != null){
result.append(line);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
//利用HttpClient进行http的api调用
//利用Post提交
public static String getResponseByHttpClient_Post(String serverUrl) throws IOException {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();//对HttpClient的配置
cm.setMaxTotal(200);// 最大连接数
cm.setDefaultMaxPerRoute(20);//每个路由基础的连接
HttpClient httpClientDeprecated = new DefaultHttpClient();//DefaultHttpClient方式
HttpClient httpClientHttps = HttpClients.custom().setConnectionManager(cm).build();
HttpClient HttpClient = HttpClientBuilder.create().build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();//HttpClient jar在4.3版本以后,DefaultHttpClient 被 deprecated(不推荐),用HttpClientBuilder替代
String response = "";
HttpPost httpPost = new HttpPost(serverUrl);//POST请求:
List params = new ArrayList();
params.add(new BasicNameValuePair("origin","120.173513,30.182344"));
params.add(new BasicNameValuePair("destination","120.17971,30.187726"));
params.add(new BasicNameValuePair("size","3"));
params.add(new BasicNameValuePair("key","30bfe2cb061e2abb25fc2af3fab04227"));
UrlEncodedFormEntity urlEncodEntity = new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(urlEncodEntity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);//发送请求,并返回的所有信息,保存在HttpResponse里面
System.out.println(httpResponse.getProtocolVersion());//协议版本
System.out.println(httpResponse.getStatusLine().toString());//状态行信息
System.out.println(httpResponse.getStatusLine().getStatusCode());//状态码
System.out.println(httpResponse.getStatusLine().getReasonPhrase());//状态码的解释
if (httpResponse.getStatusLine().getStatusCode()==200){//取出服务器返回的状态码,等于200就说明请求和响应成功
HttpEntity entity = httpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
response = EntityUtils.toString(entity,"utf-8");//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
}
httpResponse.close();
httpClient.close();
return response;
}
//利用HttpClient进行http的api调用
//利用Get提交
public static String getResponseByHttpClient_Get(String serverUrl) throws IOException {
HttpClient httpClientDeprecated = new DefaultHttpClient();//DefaultHttpClient方式
HttpClient httpClientBuilder = HttpClientBuilder.create().build();//HttpClient方式 jar在4.3版本以后,DefaultHttpClient 被 deprecated(不推荐),用HttpClientBuilder替代
String response = "";
HttpGet httpGet = new HttpGet(serverUrl);
HttpResponse httpResponse = httpClientBuilder.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity entity = httpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
response = EntityUtils.toString(entity,"utf-8");
}
httpClientBuilder.getConnectionManager().shutdown();//关闭连接
//Get方式与Post方式最大的区别为:
//Post方式需要list的集合来存放api所需要的参数,(注意:HttpPost方式也可以用URL方式传参)
//Get方式直接在访问路径内附带参数即可,(注意:HttpGet方式也可以用Body方式传参)
return response;
}
}
注:
该test类是我自己在理解HttpURLConnection与HttpClient时写的test。