文章积累知识,如有存在问题,请大家不啬赐教
import com.hbxhx.utils.string.StringUtils;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MyHttpUtils {
/**
* post application/json
*
* @param urlstr
* @param jsonstr
* @return
* @throws Exception
*/
public static String getMarketingPost(String urlstr, String jsonstr) throws Exception {
PostMethod post = new PostMethod(urlstr);
RequestEntity entity = new StringRequestEntity(jsonstr, "application/json", "utf-8");
post.setRequestEntity(entity);
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
String result = null;
InputStream inputStream = null;
InputStreamReader reader = null;
BufferedReader br = null;
try {
int statusCode = httpClient.executeMethod(post);
if (statusCode == HttpStatus.SC_OK) {
inputStream = post.getResponseBodyAsStream();
reader = new InputStreamReader(inputStream, "UTF-8");
br = new BufferedReader(reader);
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
result = stringBuffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception("发生IO异常");
} finally {
if (br != null) {
br.close();
}
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
post.releaseConnection();
}
return result;
}
/**
* post application/json token
*
* @param urlstr
* @param jsonstr
* @param token
* @return
* @throws Exception
*/
public static String getMarketingPost(String urlstr, String jsonstr, String token) throws Exception {
PostMethod post = new PostMethod(urlstr);
post.setRequestHeader("pplmc-app-token", token);
RequestEntity entity = new StringRequestEntity(jsonstr, "application/json", "utf-8");
post.setRequestEntity(entity);
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
String result = null;
InputStream inputStream = null;
InputStreamReader reader = null;
BufferedReader br = null;
try {
int statusCode = httpClient.executeMethod(post);
if (statusCode == HttpStatus.SC_OK) {
inputStream = post.getResponseBodyAsStream();
reader = new InputStreamReader(inputStream, "UTF-8");
br = new BufferedReader(reader);
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
result = stringBuffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception("发生IO异常");
} finally {
if (br != null) {
br.close();
}
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
post.releaseConnection();
}
return result;
}
/**
* get普通请求 不传参数 携带token
*
* @param url
* @param token
* @return
* @throws Exception
*/
public static String doGet(String url, String token) throws Exception {
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("pplmc-app-token", token);
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
/**
* get 表单请求 携带token
* @param url
* @param token
* @param param
* @return
*/
public static String doGet(String url, String token, BeanMap param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (Object key : param.keySet()) {
String s = String.valueOf(param.get(key));
if (!StringUtils.isEmpty(s)) {
builder.addParameter(key.toString(), String.valueOf(param.get(key)));
}
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpGet.addHeader("pplmc-app-token", token);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "multipart/form-data;");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return String 所代表远程资源的响应结果
*/
public static String get(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
//System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
/*for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}*/
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 以form表单形式提交数据,发送post请求
*
* @param url 请求地址
* @param paramsMap 具体数据
* @return 服务器返回数据
* @explain 1.请求头:httppost.setHeader("Content-Type","application/x-www-form-urlencoded")
* 2.提交的数据格式:key1=value1&key2=value2...
*/
public static String httpPostWithForm(String url, Map<String, String> paramsMap) {
// 用于接收返回的结果
String resultData = "";
try {
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
// 迭代Map-->取出key,value放到BasicNameValuePair对象中-->添加到list中
for (String key : paramsMap.keySet()) {
pairList.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList, "utf-8");
post.setEntity(uefe);
// 创建一个http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 发送post请求
HttpResponse response = httpClient.execute(post);
// 状态码为:200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回数据:
resultData = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
throw new RuntimeException("接口连接失败!");
}
} catch (Exception e) {
throw new RuntimeException("接口连接失败!");
}
return resultData;
}
}