private static HttpClientContext context = HttpClientContext.create();
/**
* http async get
*
* @param url
* @param data
* @return
*/
public static void doGet(String url, String data) {
CookieStore cookieStore = new BasicCookieStore();
final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
HttpGet httpGet = new HttpGet(url);
//httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httpClient.execute(httpGet, context, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
String body="";
//这里使用EntityUtils.toString()方式时会大概率报错,原因:未接受完毕,链接已关
try {
HttpEntity entity = result.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
try {
final StringBuilder sb = new StringBuilder();
final char[] tmp = new char[1024];
final Reader reader = new InputStreamReader(instream,"UTF-8");
int l;
while ((l = reader.read(tmp)) != -1) {
sb.append(tmp, 0, l);
}
body = sb.toString();
System.out.println(body);
} finally {
instream.close();
EntityUtils.consume(entity);
}
}
} catch (ParseException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
close(httpClient);
}
}
@Override
public void failed(Exception ex) {
System.out.println(ex.toString());
close(httpClient);
}
@Override
public void cancelled() {
}
});
} catch (Exception e) {
}
System.out.println("end-----------------------");
}
/**
* http async post
*
* @param url
* @param values
* @return
*/
public static void doPost(String url, List<NameValuePair> values) {
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
httpPost.setEntity(entity);
try {
httpClient.execute(httpPost, context, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
System.out.println(result.toString());
}
@Override
public void failed(Exception ex) {
System.out.println(ex.toString());
}
@Override
public void cancelled() {
}
});
} catch (Exception e) {
}
}
private static void close(CloseableHttpAsyncClient client) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 直接把Response内的Entity内容转换成String
*
* @param httpResponse
* @return
*/
public static String toString(CloseableHttpResponse httpResponse) {
// 获取响应消息实体
String result = null;
try {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000) //连接超时,连接建立时间,三次握手完成时间
.setSocketTimeout(50000) //请求超时,数据传输过程中数据包之间间隔的最大时间
.setConnectionRequestTimeout(1000) //使用连接池来管理连接,从连接池获取连接的超时时间
.build();
//配置io线程
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setSoKeepAlive(true)
.build();
//设置连接池大小
ConnectingIOReactor ioReactor = null;
try {
ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
} catch (IOReactorException e) {
e.printStackTrace();
}
PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(100);
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig).build();
try {
httpclient.start();
//String url = "https://webpaywg.bestpay.com.cn/barcode/placeOrder";
//HttpGet request = new HttpGet("http://www.apache.org/");
String url = "http://localhost:8080/pay_info";
HttpPost httpPost = new HttpPost(url);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String date_time = simpleDateFormat.format(new Date());
System.out.println("date_time = " + date_time);
String key = "ABCDEF";
String merchant_id = "987946459879";
String order_no = "2018082700012";
String order_req_no = "111113";
String barcode = "510267678301150238";
String order_amt = "1";
String sign = "MERCHANTID=" + merchant_id + "&ORDERNO=" + order_no + "&ORDERREQNO=" + order_req_no + "&ORDERDATE=" + date_time + "&BARCODE=" + barcode + "&ORDERAMT=" + order_amt + "&KEY=" + key;
String content = "merchantId=" + merchant_id + "&barcode=" + barcode + "&orderNo=" + order_no + "&orderReqNo=" + order_req_no + "&channel=05&busiType=0000001&orderDate=" + date_time + "&orderAmt=" + order_amt + "&productAmt=1&attachAmt=0&storeId=123&mac=" + MD5(sign);
StringEntity postEntity = new StringEntity(content);
postEntity.setContentType("application/x-www-form-urlencoded");
//httpPost.setHeader("content-type","application/json");
Future<HttpResponse> future = httpclient.execute(httpPost, null);
httpPost.setEntity(postEntity);
HttpResponse response = future.get();
System.out.println("Response: " + response.getStatusLine());
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
System.out.println("Response Data:" + result);
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
private static String MD5(String s) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(s.getBytes("utf-8"));
return toHex(bytes);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String toHex(byte[] bytes) {
final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
StringBuilder ret = new StringBuilder(bytes.length * 2);
for (int i=0; i<bytes.length; i++) {
ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
}
return ret.toString();
}
CloseableHttpAsyncClient
最新推荐文章于 2024-04-28 21:43:57 发布