java 后台代码调用接口



import com.jiuqu.jollykeys.common.util.JsonUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.*;

import org.springframework.stereotype.Service;

/**
* @author cloud
* @description
* @date 2017年06月15日
*/
@Service
public class HttpClientService {

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

@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig requestConfig;

/**
* 处理get请求.
*
* @param url 请求路径
* @return json
*/
public String get(String url) {
logger.info("请求地址(get):" + url);
//请求结果
String content = "";
try {
//实例化get方法
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
//执行get方法
CloseableHttpResponse response = httpClient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("HTTP请求返回参数(get):" + content);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

/**
* 处理get请求.
*
* @param url 请求路径
* @param headers 请求头信息
* @param params 请求参数
*/
public String get(String url, Map<String, String> headers, Map<String, String> params) {
logger.info("请求地址(get):" + url);
logger.info("请求参数(get):" + JsonUtil.gson.toJson(params));
String content = "";
try {
//实例化get方法
HttpGet httpget = new HttpGet(buildUrl(url, params));
httpget.setConfig(requestConfig);
//设置请求头
for (Map.Entry<String, String> e : headers.entrySet()) {
httpget.addHeader(e.getKey(), e.getValue());
}

CloseableHttpResponse response = httpClient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("HTTP请求返回参数(get):" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}

/**
* 处理post请求.
*
* @param url 请求路径
* @param params 参数
* @return json
*/
public String post(String url, Map<String, String> params) {
logger.info("请求地址(post):" + url);
logger.info("请求参数(post):" + JsonUtil.gson.toJson(params));
//结果
String content = "";
try {
//实例化post方法
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//处理参数
List<NameValuePair> nvps = new ArrayList<>();
if (params != null) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
}
//提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
//将参数给post方法
httpPost.setEntity(uefEntity);
//执行post方法
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("HTTP请求返回参数(post):" + content);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

public String post2(String url, Map<String, Object> params) {
logger.info("请求地址(post):" + url);
logger.info("请求参数(post):" + JsonUtil.gson.toJson(params));
//结果
String content = "";
try {
//实例化post方法
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//处理参数
List<NameValuePair> nvps = new ArrayList<>();
if (params != null) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key,params.get(key).toString));
}
}
//提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
//将参数给post方法
httpPost.setEntity(uefEntity);
//执行post方法
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("HTTP请求返回参数(post):" + content);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

/**
* 处理post请求.
*
* @param url 请求路径
* @param params 参数
* @return json
*/
public String post(String url, Map<String, String> headers, Map<String, String> params) {
logger.info("请求地址(post):" + url);
logger.info("请求参数(post):" + JsonUtil.gson.toJson(params));
//结果
String content = "";
try {
//实例化post方法
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);

for (Map.Entry<String, String> e : headers.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}

//处理参数
List<NameValuePair> nvps = new ArrayList<>();
if (params != null) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
}
//提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
//将参数给post方法
httpPost.setEntity(uefEntity);
//执行post方法
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("HTTP请求返回参数(post):" + content);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

private static String buildUrl(String host, Map<String, String> querys)
throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}

return sbUrl.toString();
}

public static String do_post(String url, List<NameValuePair> name_value_pair) throws IOException {
         String body =  "{}" ;
         DefaultHttpClient httpclient =  new  DefaultHttpClient();
         try  {
             HttpPost httpost =  new  HttpPost(url);
             httpost.setEntity( new  UrlEncodedFormEntity(name_value_pair, StandardCharsets.UTF_8));
             HttpResponse response = httpclient.execute(httpost);
             HttpEntity entity = response.getEntity();
             body = EntityUtils.toString(entity);
         finally  {
             httpclient.getConnectionManager().shutdown();
         }
         return  body;
     }
     public  static  String do_get(String url)  throws  ClientProtocolException, IOException {
         String body =  "{}" ;
         DefaultHttpClient httpclient =  new  DefaultHttpClient();
         try  {
             HttpGet httpget =  new  HttpGet(url);
             HttpResponse response = httpclient.execute(httpget);
             HttpEntity entity = response.getEntity();
             body = EntityUtils.toString(entity);
         finally  {
             httpclient.getConnectionManager().shutdown();
         }
         return  body;
     }
}

转载于:https://www.cnblogs.com/zhengwuchao/p/8052528.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值