话不多说,上代码
package com.ewe.core.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import com.ewe.core.exception.CustomException;
public final class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
public static final String UTF_8 = "UTF-8";
public static final String GB2312 = "gb2312";
private HttpUtils() {
}
private static RequestConfig REQUEST_CONFIG = RequestConfig.custom().setConnectTimeout(Integer.parseInt(DictUtils.HTTP_TIME_OUT)).setSocketTimeout(Integer.parseInt(DictUtils.HTTP_TIME_OUT)).build();
/**
* Encode the URL with UTF-8 URLEncoder
*
* @param url
* @return
*/
public static final String encodeURL(final String url) {
String result;
try {
result = URLEncoder.encode(url, UTF_8);
} catch (UnsupportedEncodingException e) {
result = StringUtils.EMPTY;
}
return result;
}
/**
* Internal Method
*
* @param httpclient
* @param httpRequest
* @param responseEncoding
* @return
*/
private static final String request(final CloseableHttpClient httpclient, final HttpUriRequest httpRequest, final String responseEncoding, final Map<String, String> headers) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Executing request " + httpRequest.getRequestLine());
}
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> map : headers.entrySet()) {
httpRequest.addHeader(map.getKey(), map.getValue());
}
}
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if(status==500){
throw new CustomException("内部服务器错误!", HttpStatus.INTERNAL_SERVER_ERROR);
}else if(status==404){
throw new CustomException("请求的资源不存在!", HttpStatus.INTERNAL_SERVER_ERROR);
}else if(status==503){
throw new CustomException("由于超载或系统维护,服务器暂时的无法处理客户端的请求!", HttpStatus.INTERNAL_SERVER_ERROR);
}
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity, responseEncoding) : null;
}
};
String responseBody = httpclient.execute(httpRequest, responseHandler);
if (logger.isDebugEnabled()) {
logger.debug("----------------------------------------");
logger.debug(responseBody);
}
return responseBody;
} catch (IOException e) {
logger.error("HTTP execute failed", e);
throw new CustomException("请求执行失败,Jerry服务器路径错误,无法返回请求结果!", HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
try {
httpclient.close();
} catch (IOException e) {
}
}
}
/**
* GET or Post
* @param url
* @param param
* @param headers
* @return
* @throws Exception
*/
public static final String request(final String url, final Map<String, String> param,final Map<String,String> headers,String method,StringEntity stringEntity) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
URIBuilder builder;
builder = new URIBuilder(url);
for (Map.Entry<String, String> map : param.entrySet()) {
builder.setParameter(map.getKey(), map.getValue());
}
if(DictUtils.GET.equalsIgnoreCase(method)){
HttpGet get = new HttpGet(builder.build());
get.setConfig(REQUEST_CONFIG);
return request(client, get, UTF_8, headers);
}
else if(DictUtils.POST.equalsIgnoreCase(method)){
HttpPost post = new HttpPost(builder.build());
post.setEntity(stringEntity);
return request(client, post, UTF_8, headers);
}else{
return null;
}
}
public static void main(String[] args) {
// 测试数据
}
}
如果有帮助,点歌赞,希望能帮到你
案例如下
package com.ewe.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ewe.core.exception.CustomException;
import com.ewe.core.utils.DictUtils;
import com.ewe.core.utils.HttpUtils;
import com.ewe.core.utils.TokenUtil;
@RestController
public class AppController{
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
@Value("${${active}.app.jerry.host}")
private String host;
@Value("${app.replace.uri}")
private String replaceUri;
@Value("${app.resource.uri}")
private String resourceUri;
/**
*
* @param request
* @param response
* @throws Exception
* spring 会先适配存在的uri 如果不存在 统一转发到这个地方
*/
@RequestMapping(value="/**")
public void request(HttpServletRequest request,HttpServletResponse response) throws Exception{
LOGGER.info("开始请求转发数据");
String body = doPostAndGet(request);
LOGGER.info("转发数据封装处理为JSON ,当前的返回body是:{}字符集是:UTF-8",body);
// 如果当前的数据是json 目前先设置这种格式的数据
response.setContentType(DictUtils.CONTENT_TYPE_JSON);
response.setCharacterEncoding("UTF-8");
PrintWriter writer=response.getWriter();
if(body.contains("<html>")&&body.contains("<head>")&&body.contains("<title>")){
JSONObject result = new JSONObject();
result.put("code", "500");
result.put("message", dealWith(body));
writer.println(result.toJSONString());
}
else{
writer.println(body);
}
writer.close();
LOGGER.info("返回数据结束!");
}
/**
* 对网页返回得到数据进行处理
* @param html
* @return
*/
private String dealWith(String html){
int start = html.indexOf("<b>description</b> <u>");
int end = html.indexOf("</u></p><HR size=");
String info = html.substring("<b>description</b> <u>".length()+start,end);
if(info.contains("HTTP method is not allowed")){
info="请求方式不对,请检查请求的方式!";
}else if(info.contains("syntactically incorrect")){
info="客户端发送的请求在语法上不正确,请使用合法参数!";
}
LOGGER.error("错误的信息是:{}",info);
return info;
}
/**
* 开始转发原来数据
* @param request
* @param response
* @return
* @throws Exception
*/
private String doPostAndGet(HttpServletRequest request) throws Exception{
String path= request.getRequestURI();
// 如果springSecurity 找不到这个url的权限 就会重新定向到 一个url 如果是我指定的 就说资源不存在或者你没有权限。
if(DictUtils.UN_EXIST_URL.equalsIgnoreCase(path)){
JSONObject result = new JSONObject();
result.put("code", "404");
result.put("message", "无效的URL");
return result.toJSONString();
}
String method = request.getMethod();//得到请求URL地址时使用的方法
// request.get
Map<String,String> parms = new HashMap<String, String>();
// 遍历请求的参数
for(Enumeration<String> e=request.getParameterNames();e.hasMoreElements();){
String thisName=e.nextElement().toString();
String thisValue=request.getParameter(thisName);
parms.put(thisName, thisValue);
}
// headers参数
Map<String,String> headers = new HashMap<String, String>();
boolean flagTimezone=false;
for(Enumeration<String> e=request.getHeaderNames();e.hasMoreElements();){
String thisName=e.nextElement().toString();
String thisValue=request.getHeader(thisName);
// 时区
if(DictUtils.TIMEZONE.equalsIgnoreCase(thisName)){
LOGGER.info("当前的时区是:{}",thisValue);
headers.put(DictUtils.TIMEZONE, thisValue);
flagTimezone=true;
}
}
if(!flagTimezone){
throw new CustomException("头部没有时区,请加入Timezone", HttpStatus.INTERNAL_SERVER_ERROR);
}
headers.put("Username", TokenUtil.getUserName(TokenUtil.resolveToken(request)));
headers.put("Content-type", DictUtils.CONTENT_TYPE_JS);
LOGGER.info("当前的uri是:{},methd:{},parms:{},headers:{}",path,method,parms.toString(),headers.toString());
// body
BufferedReader reader = request.getReader();
String readerStr = "";// 接收用户端传来的JSON字符串(body体里的数据)
String line;
while ((line = reader.readLine()) != null){
readerStr = readerStr.concat(line);
}
// post才需要这个json数据
StringEntity stringEntity = new StringEntity(readerStr,DictUtils.ENCODING_UTF_8);
stringEntity.setContentType(DictUtils.CONTENT_TYPE_JS);
stringEntity.setContentEncoding(DictUtils.ENCODING_UTF_8);
// 开始请求数据
String url = host+path;
// 当前的uri再加上 隐藏
url=url.replaceAll(resourceUri, replaceUri);
LOGGER.info("请求jerry路径:{}",url);
String entity = HttpUtils.request(url, parms, headers, method, stringEntity);
return entity;
}
}