HTTP的各种请求(get、post、form)

package com.pay.paydemo.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
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.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

/**
* @ClassName:HttpClientManager
* @Description:httpClient客户端 post entity的几种形式:
* BasicHttpEntity 代表底层流的基本实体 InputStream流数据
* ByteArrayEntity 从指定的字节数组中取出内容的实体
* StringEntity 自我包含的可重复的实体,格式灵活(json、xml等)
* InputStreamEntity 流式不可以重复的实体
* UrlEncodedFormEntity 数据为键值对
*/

public class HttpClientManager {

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

private static HttpClientManager httpClientManager = new HttpClientManager();

private static HttpClient httpClient = HttpClientManager.createHttpclient();

// 创建 httpClient
private static HttpClient createHttpclient(int connectTimeout, int connectionRequestTimeout) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500); // 最大连接数
cm.setDefaultMaxPerRoute(200);
// cm.setValidateAfterInactivity(2000);//设置空闲连接回收时间(单位ms),默认2000 连接是放linklist,使用的时候检查是否过期,拿到可用的连接会从头部移到尾部,所以回收时间会影响到服务器存在CLOSE_WAIT的个数
// CookieStore cookieStore = new BasicCookieStore();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout) //请求超时时间
.setSocketTimeout(10 * 1000) //等待数据超时时间
.setConnectionRequestTimeout(connectionRequestTimeout) //获取连接超时时间
.build();
return HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(requestConfig)
// .setDefaultCookieStore(cookieStore) //设置cookie保持会话
.build();
}

// 创建 httpClient
private static HttpClient createHttpclient() {
return createHttpclient(5 * 1000, 3 * 1000);
}

private HttpClientManager() {

}

public static HttpClientManager getInstance() {
return HttpClientManager.httpClientManager;
}

public static String httpGet(String url, String returnCharset) throws IOException {
return httpGet(url, returnCharset, 5000);
}

public static String httpGet(String url, String returnCharset, int connectTimeout) throws IOException {
logger.info("请求URL:" + url);
long ls = System.currentTimeMillis();
HttpGet httpGet = null;
String result = "";
try {
httpGet = new HttpGet(url);

HttpResponse response = createHttpclient(connectTimeout, connectTimeout).execute(httpGet);

for (Header header : response.getAllHeaders()) {
logger.debug(header.getName() + ":" + header.getValue());
}

int code = response.getStatusLine().getStatusCode();
logger.info("服务器返回的状态码为:" + code);
HttpEntity entity = response.getEntity();
if (code == HttpStatus.SC_OK || entity != null) {// 如果请求成功
if (S.isBlank(returnCharset)) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), returnCharset);
}
}


} finally {
if (null != httpGet) {
httpGet.releaseConnection();
}
long le = System.currentTimeMillis();
logger.info("返回数据为:" + result);
logger.info("http请求耗时:" + (le - ls) + "ms");
}
return result;
}


/**
* @param url 请求url
* @param s 请求数据
* @param contentType
* @return String
* @throws
* @Title: httpPost
* @Description: http post请求,
* StringEntity Content-Type=application/json;charset=utf-8
*/
public static String httpPost(String url, String s, String contentType) throws IOException {
logger.info("请求URL:{},{}", url, s);
long ls = System.currentTimeMillis();
HttpPost httpPost = null;
String result = "";
try {
httpPost = new HttpPost(url);
StringEntity param = new StringEntity(s, "UTF-8");
param.setContentEncoding("UTF-8");
httpPost.setEntity(param);

if (S.isBlank(contentType)) {
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
} else {
httpPost.setHeader("Content-Type", contentType);
}
HttpResponse response = httpClient.execute(httpPost);

int code = response.getStatusLine().getStatusCode();
logger.info("服务器返回的状态码为:{}", code);

if (code == HttpStatus.SC_OK) {// 如果请求成功
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}

} finally {
if (null != httpPost) {
httpPost.releaseConnection();
}
long le = System.currentTimeMillis();
logger.info("返回数据为:{}", result);
logger.info("http请求耗时: {} ms", (le - ls));
}
return result;
}

/**
* @param @param url
* @param @return
* @return String
* @throws
* @Title: httpPostWithHead
* @Description: http post请求,能自定义请求头
* ByteArrayEntity Content-Type=utf-8
*/
public static String httpPostWithHead(String url, Map<String, Object> headers, String body) {
logger.info("请求URL:{},请求head:{},请求数据:{}", url, headers, body);
long ls = System.currentTimeMillis();
HttpPost post = null;
String result = "";
try {
post = new HttpPost(url);
for (Map.Entry<String, Object> e : headers.entrySet()) {
post.addHeader(e.getKey(), String.valueOf(e.getValue()));
}
post.setEntity(new ByteArrayEntity(body.getBytes("utf-8")));
HttpResponse response = httpClient.execute(post);

for (Header header : response.getAllHeaders()) {
logger.info(header.getName() + ":" + header.getValue());
}

int code = response.getStatusLine().getStatusCode();
logger.info("服务器返回的状态码为:" + code);

if (code == HttpStatus.SC_OK) {// 如果请求成功
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}

return result;

} catch (Exception e) {
logger.error(e.getMessage());
return result;
} finally {
if (null != post) {
post.releaseConnection();
}
long le = System.currentTimeMillis();
logger.info("返回数据为:" + result);
logger.info("http请求耗时:" + (le - ls) + "ms");
}

}

/**
* @param @param params
* @param @return
* @return List<NameValuePair>
* @throws @Title: transformMap
* @Description: 转换post请求参数
*/
private static List<NameValuePair> transformMap(Map<String, String> params) {
if (params == null || params.size() < 0) {// 如果参数为空则返回null;
return new ArrayList<NameValuePair>();
}
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> map : params.entrySet()) {
paramList.add(new BasicNameValuePair(map.getKey(), map.getValue()));
}
return paramList;
}

/**
* @param @param url
* @param @return
* @return String
* @throws
* @Title: httpPost
* @Description: http post请求,
* UrlEncodedFormEntity Content-Type=application/x-www-form-urlencoded
*/
public static String httpPostByForm(String url, Map<String, String> formParam) throws IOException {
return httpPostbyFormHasProxy(url, formParam, null, null, null);
}

/*
* returnCharset 指定返回报文编码
* */
public static String httpPostByForm(String url, Map<String, String> formParam, String returnCharset, String head) throws IOException {
return httpPostbyFormHasProxy(url, formParam, null, returnCharset, head);
}

/**
* @param @param url
* @param @param formParam
* @param @param proxy
* @param @return
* @return String
* @throws
* @Title: httpPost
* @Description: http post请求
* UrlEncodedFormEntity Content-Type=application/x-www-form-urlencoded
*/
public static String httpPostbyFormHasProxy(String url, Map<String, String> formParam, HttpHost proxy, String returnCharset, String head) throws IOException {

logger.info("请求URL:{}", url);
long ls = System.currentTimeMillis();
HttpPost httpPost = null;
String result = "";
try {

httpPost = new HttpPost(url);
if (!S.isBlank(head)) {
httpPost.setHeader("Referer", head);
}
if (proxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
httpPost.setConfig(config);
}

List<NameValuePair> paramList = transformMap(formParam);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, "utf8");
httpPost.setEntity(formEntity);

HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
logger.info("服务器返回的状态码为:{}", code);

if (code == HttpStatus.SC_OK) {// 如果请求成功
if (S.isBlank(returnCharset)) {
result = EntityUtils.toString(httpResponse.getEntity());
} else {
result = EntityUtils.toString(httpResponse.getEntity(), returnCharset);
}
}
/* 303和307是HTTP1.1新加的服务器响应文档的状态码,它们是对HTTP1.0中的302状态码的细化,主要用在对非GET、HEAD方法的响应上。
* 302 必须跟用户确认是否该重发,因为第二次POST时,环境可能已经发生变化(嗯,POST方法不是幂等的),POST操作会不符合用户预期。但是,很多浏览器(user agent我描述为浏览器以方便介绍)在这种情况下都会把POST请求变为GET请求
* 303 POST重定向为GET
* 307 当客户端的POST请求收到服务端307状态码响应时,需要跟用户询问是否应该在新URI上发起POST方法,也就是说,307是不会把POST转为GET的
* */
if (code == 307) {
Header header = httpResponse.getFirstHeader("Location");
logger.info("redirect url: " + header.getValue());
result = httpPostbyFormHasProxy(header.getValue(), formParam, null, returnCharset, head);
} else if (code == 302) {
Header header = httpResponse.getFirstHeader("Location");
logger.info("redirect url: " + header.getValue());
if (header.getValue().startsWith("/Cashier/Error.aspx") || header.getValue().startsWith("/Common/H5/Error.aspx?")) {
String s = header.getValue().split("\\?")[1].split("=")[1];
return unicode2String(s);
}
if (header.getValue().startsWith("https://") || header.getValue().startsWith("http://")) {
return header.getValue();
}
String targetUrl = "https://pay.heepay.com/" + header.getValue();
if (header.getValue().contains("/MSite/Cashier/AliPayWapPay")) {
return targetUrl;
}
result = httpPostbyFormHasProxy(targetUrl, formParam, null, returnCharset, head);
} else if (code == 303) {
Header header = httpResponse.getFirstHeader("Location");
logger.info("redirect url: " + header.getValue());
result = httpGet(header.getValue(), null);
}
} finally {
if (null != httpPost) {
httpPost.releaseConnection();
}
long le = System.currentTimeMillis();
logger.info("返回数据为:{}", result);
logger.info("http请求耗时:ms", (le - ls));
}
return result;

}

public static String unicode2String(String unicode) {
if (unicode.contains("%"))
unicode = unicode.replaceAll("%", "\\\\");
StringBuilder string = new StringBuilder();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 转换出每一个代码点
int data = Integer.parseInt(hex[i], 16);
string.append((char) data);
}
return string.toString();
}

public static JSONObject postWithJson(String url, String json) {
String retMsg = null;
try {
retMsg = httpPost(url, json, null);
} catch (IOException e) {
logger.error("HttpClientManager>>postWithJson>>请求失败!", e);
}
if (!S.isBlank(retMsg)) {
return JSONObject.parseObject(retMsg);
}
return null;
}

public static String postJson(String url, String s, BiConsumer<Integer, String> consumer) {
HttpPost httpPost = new HttpPost(url);
logger.debug("请求的参数为: {}", s);
StringEntity param = new StringEntity(s, "utf-8");
param.setContentEncoding("utf-8");
httpPost.setEntity(param);
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
String result = null;
try {
HttpResponse response = httpClient.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
logger.debug("服务器返回的状态码为:", code);
if (code == HttpStatus.SC_OK) {// 如果请求成功
result = EntityUtils.toString(response.getEntity(), "utf-8");
logger.debug("返回数据为:{}", result);
}
if (consumer != null)
consumer.accept(code, result);
} catch (Exception e) {
logger.info("发送通知报文异常", e);
} finally {
httpPost.releaseConnection();
}
return result;
}

}

支付宝请求:
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;



AlipayClient alipayClient = new DefaultAlipayClient(map.get("requestUrl"), map.get("merNo"), map.get("sk"),
"json", ConstantPay.CHARSET_UTF8, map.get("publicKey"), getRSAType(map.get("signType"))); // 获得初始化的AlipayClient
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();// 创建API对应的request类
request.setNotifyUrl(getCallbackUrl(map.get("billId"), map.get("appId"), map.get("notifyUrl")));
request.setBizContent(getBizContent(map));// 设置业务参数

Map<String, String> result = new HashMap<String, String>();
AlipayTradePrecreateResponse response = alipayClient.execute(request);
logger.info("ALIGF pay result:" + response.getBody());
if (null != response) {
Map<String, Object> mapTypes = JSON.parseObject(response.getBody());}

转载于:https://www.cnblogs.com/duoduo264/p/9524598.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值