httpclient中的httppost、httpget----调用接口以及main方法直接调用API接口

引用参考:
--HttpClient总结一之基本使用
[url]https://www.cnblogs.com/LuckyBao/p/6096145.html[/url]
--Java HttpClient使用小结
[url]http://blog.csdn.net/bhq2010/article/details/9210007[/url]
--HttpClient的HttpGet和HttpPost工具类
[url]http://blog.csdn.net/william_wei007/article/details/75330686[/url]
--通过 GET方式传值的时候,+号会被浏览器处理为空,需要转换为%2b
[url]https://blog.csdn.net/after_you/article/details/77834228[/url]


public class salaryPay {
public static String url = "http://192.168.5.138:8033/";// test环境
private static String check = url + "newApi/card/salaryPay";
public static void main(String[] args) {
HttpUtil.httpPost(check, null, new HttpCallBackListener() {
@Override
public void success(int response, Header[] headers, String result) {

System.out.print(response + "响应数据----" + result);
}
@Override
public void failure(int response) {
System.err.print(response);
}
});
}
}



/**
* HttpClient
*/
private static final HttpClient client= getHttpClientInstance();

/**
* 单例 使Httpclient支持https
*/
private static HttpClient getHttpClientInstance() {
X509TrustManager x509mgr = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}

@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.SSL);
sslContext.init(null, new TrustManager[] { x509mgr }, null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
logger.error("error to init httpclient", e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(200);// 客户端总并行链接最大数
connManager.setDefaultMaxPerRoute(20); // 每个主机的最大并行链接数

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(connManager);
httpClientBuilder.setSSLSocketFactory(sslsf);
return httpClientBuilder.build();
}


/**
* HttpEntity转化返回为byte数组
*
*/
private static byte[] doChangeEntity2Bytes(HttpEntity entity) throws Exception {
InputStream inputStream = null;
try {
if (entity == null || entity.getContent() == null) {
throw new RuntimeException("Response Entity Is null");
}
inputStream = entity.getContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
return out.toByteArray();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}


/**
* HttpPost
*/
private static byte[] doHttpPostFun(String address, HttpEntity paramEntity, RequestConfig config) throws Exception {
HttpPost post = new HttpPost(address);
try {
if (paramEntity != null) {
post.setEntity(paramEntity);
}
post.setConfig(config);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
int code = response.getStatusLine().getStatusCode();
throw new RuntimeException("HttpPost Request Access Fail Return Code(" + code + ")");
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new RuntimeException("HttpPost Request Access Fail Response Entity Is null");
}
return doChangeEntity2Bytes(entity);
} finally {
if (post != null) {
post.releaseConnection();
}
}
}


/**
* HttpGet
*/
private static byte[] doHttpGetFun(String address, RequestConfig config) throws Exception {
HttpGet get = new HttpGet(address);
try {
get.setConfig(config);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
int code = response.getStatusLine().getStatusCode();
throw new RuntimeException("HttpGet Access Fail , Return Code(" + code + ")");
}
response.getEntity().getContent();
return doChangeEntity2Bytes(response.getEntity());
} finally {
if (get != null) {
get.releaseConnection();
}
}
}



private static final Logger logger = LoggerFactory.getLogger(ClassDemo.class);
private static final String type = "/demo/mat/{0}/{1}/{2}/Json";
@Value("${com.demo.check.url}")
private String baseUrl;
public EntityResponse checkCardNoAndBank(EntityRequest entityRequest) throws Exception {
try {
String url = baseUrl + type;
logger.info("-->打印日志"url);
String completeUrl = MessageFormat.format(url, URLEncoder.encode(entityRequest.getName(),"utf-8"),entityRequest.getNo(),URLEncoder.encode(entityRequest.getType(),"utf-8"));
String json = HttpClientHelper.getDataByGetMethod(completeUrl);
logger.info("json Resposne >>>" + json);
return GsonUtils.convertObj(json, EntityResponse.class);
}catch (Exception e){
e.printStackTrace();
return null;
}
}




private boolean doPostFun(Map<String, String> paramsMap){
boolean rtnFlag=false;
if(null!=paramsMap&&paramsMap.isEmpty()==false){
try {
/**
* 形式1:Content-Type: text/plain; charset=UTF-8
*/
String paramJson = GsonUtils.toJson(paramsMap);
HttpEntity paramEntity = new StringEntity(paramJson.toString(),"UTF-8");
respJson = HttpClientUtils.getMethodPostResponse(url, paramEntity);
/**
* 形式2:Content-Type: application/json;charset=utf-8
*/
String paramJson = GsonUtils.toJson(paramsMap);
StringEntity entity = new StringEntity(paramJson,"UTF-8");
entity.setContentType("application/json");
//
//post请求
respJson = HttpClientUtils.getMethodPostResponse(url, entity);
logger.info("正常->" + respJson);
} catch (Exception e) {
e.printStackTrace();
logger.info("异常->" + e.getMessage());
}
ResponseDto result= GsonUtils.convertObj(respJson, ResponseDto.class);
if (null!=result&&StringUtils.isNotBlank(result.getStatus())&&"1".equals(result.getStatus())) {
//成功
logger.info("成功->cid="+paramsMap.get("cid"));
rtnFlag=true;
}else{
//失败
logger.info("失败->cid="+paramsMap.get("cid"));
}
}
return rtnFlag;
}


Http请求响应信息

=================================================================
【请求信息】
ID: 1091
Address: http://.../Info
Encoding: UTF-8
Http-Method: POST
Content-Type: application/json;charset=UTF-8
Headers: {
Accept=[application/json, text/plain, */*],
accept-encoding=[gzip, deflate],
accept-language=[zh-CN,en-US;q=0.8],
connection=[close],
Content-Length=[399],
content-type=[application/json;charset=UTF-8],
cookie=[_fmdata=4500B47041D0BFFC9DD4B420764A5B0070658214442367DF663AD941615413F75382049B327144F56CE5D4438C8A6D1FF3B248B92A2159F9],
host=[www.beta.ddcash.cn],
origin=[http://www.beta.x.cn],
referer=[http://www.beta.x.cn/],
user-agent=[Mozilla/5.0 (Linux; Android 7.0; EVA-AL10 Build/HUAWEIEVA-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043124 Safari/537.36 MicroMessenger/6.5.8.1060 NetType/WIFI Language/zh_CN],
x-forwarded-for=[10.254.30.59],
x-real-ip=[10.254.30.59],
x-requested-with=[com.tencent.mm]
}
Payload: {"name":"value"}
【响应信息】
ID: 1091
Response-Code: 200
Content-Type: application/json;charset=utf-8
Headers: {Content-Type=[application/json;charset=utf-8], Date=[Tue, 04 Jul 2017 17:14:55 GMT]}
Payload: {
"name":"value"
}
=================================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值