工具类–HttpUtil
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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 org.junit.Test;
import com.core.config.JsonUtil;
import com.core.config.pay.PayDigestUtil;
/**
* HttpUtil-工具类
* @author yuelong
*
*/
public class HttpUtil {
/**
* post请求
*/
@Test
public static String doPost(String uri,Map<String,Object> map) {
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 创建一个提交数据的容器
List<BasicNameValuePair> parames = new ArrayList<>();
for(String key : map.keySet()){
String value = map.get(key).toString();
parames.add(new BasicNameValuePair(key,value));
}
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
client = HttpClients.createDefault();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(">>>>>result》》》"+result+"!!!!!");
return result;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
/**
* post请求(Content-Type=application/x-www-form-urlencoded),使用原生HttpURLConnection实现post请求
* @param url
* @param parameterData
* @return
* @throws Exception
*/
public static String doPost1(String url,String parameterData) throws Exception {
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.setReadTimeout(6000);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
/**
* post请求(用于请求json格式的参数,Content-Type=application/x-www-form-urlencoded),使用CloseableHttpClient实现post请求
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "*/*");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
System.err.println("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* post请求(用于请求json格式的参数,Content-Type=application/json),使用CloseableHttpClient实现post请求)
* @param url
* @param params
* @return
*/
public static String doPost2(String url, String params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
System.err.println("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "请求失败";
}
public static void main(String[] args) throws Exception {
//盛京银行账户检查参数
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("cardNo", "6231080303421812"); //盛京银行卡号
paramMap.put("limitation", "7"); //拉取乘车码账户最低金额,gateWayApp服务传入
//签名
String reqSign = PayDigestUtil.shengjingGetSign(paramMap);
paramMap.put("sign", reqSign);
String result = HttpUtil.doPost1("http://16.7.65.75:8888/sjtapp/queryAccount", JsonUtil.toJson(paramMap));
System.out.println(result);
}
}