加载中...
加载中...
HTTP工具类

HTTP工具类1

复制收展Javapackage com.nstc.aims.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;


/**
*
* <p>Title: </p>
*
* <p>Description: HTTP工具类 </p>
*
*
* @author luolei
*
* @since:2021年7月24日
*
*/
public class HttpRequest {
private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

private static class TrustAnyTrustManager implements X509TrustManager {

public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}

private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数 JSON
* @return 所代表远程资源的响应结果
*/
public static Map post(String url, String param) {
return post(url, param, null);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数 JSON
* @param cookie
* 携带cookie
* @return 所代表远程资源的响应结果
*/
public static Map post(String url, String param, String cookie) {
logger.info("请求路径:"+url+", 请求参数:"+param);
if(false){
return virtualResponse();
}
Map<String, String> result = new HashMap();
OutputStreamWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(url);
//HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
HttpURLConnection conn=null;
if (url.startsWith("https")){
//https方式提交需要
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());
HttpsURLConnection con = (HttpsURLConnection) realUrl.openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
con.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn=con;
}else{
conn= (HttpURLConnection) realUrl.openConnection();
}

// 打开和URL之间的连接
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // POST方法

// 设置通用的请求属性
//conn.setRequestProperty("accept", "*/*");
//conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setRequestProperty("Content-Type", "application/json"); // 设置内容类型
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.addRequestProperty("Connection", "keep-alive");
conn.addRequestProperty("Accept", "*/*");
if (cookie != null) {
conn.addRequestProperty("Cookie", cookie);//设置cookie
}
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
String resultStr="";
while ((line = in.readLine()) != null) {
resultStr += line;
}
result.put("body", resultStr);
// 获取Cookie
String key = null;
for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
if (key.equalsIgnoreCase("Set-Cookie")) {
String tempCookieVal = conn.getHeaderField(i);
if (tempCookieVal.startsWith("kdservice-sessionid")) {
result.put("cookie", tempCookieVal);
break;
}
}
}
} catch (Exception e) {
logger.info("发送 POST 请求出现异常!"+e);
e.printStackTrace();
logger.info("发送异常:"+ ExceptionUtils.getFullStackTrace(e));
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
logger.info("发送异常:"+ ExceptionUtils.getFullStackTrace(ex));
}
}
logger.info("请求返回:"+result);
return result;
}

private static Map virtualResponse() {
Map<String, Object> result = new HashMap();
JSONObject body = new JSONObject();
body.put("retCode", "0000");
body.put("retMessage", "成功");
body.put("tranDate", "20211020");
result.put("body", body.toString());
return result;
}


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182

HTTP工具类2

复制收展Javapackage com.nstc.aims.util;
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.HttpPost;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
*
* <p>Title: </p>
*
* <p>Description: HTTP工具类 </p>
*
*
* @author luolei
*
* @since:2021年10月29日
*
*/
public class HttpClientRequest {

private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

/**
* 以表单形式请求
* @param url
* @param mapData
* @return
*/
public static String post(String url, Map<String, String> mapData) {
logger.info("请求路径:"+url+", 请求参数:"+mapData);
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httppost
HttpPost httpPost = new HttpPost(url);
try {
// 设置提交方式
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
// 添加参数
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (mapData.size() != 0) {
// 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
Set keySet = mapData.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
String k = (String) it.next();// key
String v = mapData.get(k);// value
nameValuePairs.add(new BasicNameValuePair(k, v));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8));
logger.info("nameValuePairs:" + nameValuePairs);
// 执行http请求
response = httpClient.execute(httpPost);
// 获得http响应体
HttpEntity entity = response.getEntity();
logger.info("entity:" + entity);
if (entity != null) {
// 响应的结果
String content = EntityUtils.toString(entity, "UTF-8");
logger.info("请求返回:" + content);
return content;
}
} catch (Exception e) {
e.printStackTrace();
}
return "获取数据错误";
}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79



 

没有更多推荐了 [去首页]
image
文章
357
原创
284
转载
73
翻译
0
访问量
199063
喜欢
47
粉丝
6
码龄
5年
资源
0

文章目录

加载中...
0
0