Commit 183cbd4a by wang_jiaxing

统一访问接口

parent 5c3ef21f
package org.springblade.founder.forward.controller;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springblade.founder.utils.HttpUtil;
import org.springblade.founder.utils.R;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* TODO
*
* @author create by lystar
* @date 2024/1/12 10:32
*/
@RestController
@RequestMapping("/forward")
public class ForwardController {
// @Value("httpUrl")
private String host = "http://127.0.0.1:9022/";
@RequestMapping("/method")
public R method(HttpServletRequest request) {
String url = request.getHeader("url");
if (StringUtils.isEmpty(url)) {
return R.error("url不能为空");
}
String type = request.getMethod();
HashMap<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String element = headerNames.nextElement();
if ("blade-auth".equals(element) || "authorization".equals(element)) {
String header = request.getHeader(element);
headers.put(element, header);
}
}
if ("post".equalsIgnoreCase(type)) {
String contentType = request.getContentType();
if ("application/json".equals(contentType)) {
try {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null) {
sb.append(inputStr);
}
String s = HttpUtil.doPostJson(host + url, headers, sb.toString());
return JSONObject.parseObject(s, R.class);
} catch (IOException e) {
e.printStackTrace();
return R.error(e.getMessage());
}
} else {
Map<String, String[]> map = request.getParameterMap();
HashMap<String, String> params = new HashMap<>();
for (String key : map.keySet()) {
String[] strings = map.get(key);
params.put(key, strings[0]);
}
try {
String s = HttpUtil.doPost(host + url, params, headers);
return JSONObject.parseObject(s, R.class);
} catch (Exception e) {
e.printStackTrace();
return R.error(e.getMessage());
}
}
} else if ("get".equalsIgnoreCase(type)) {
Map<String, String[]> map = request.getParameterMap();
StringBuilder param;
if (url.contains("?")) {
param = new StringBuilder("&");
} else {
param = new StringBuilder("?");
}
for (String key : map.keySet()) {
if (!url.contains(key)) {
String[] strings = map.get(key);
param.append(key).append("=").append(strings[0]).append("&");
}
}
try {
String substring = param.substring(0, param.length() - 1);
String s = HttpUtil.doGet(host + url + substring, headers, new HashMap<>());
return JSONObject.parseObject(s, R.class);
} catch (Exception e) {
e.printStackTrace();
return R.error(e.getMessage());
}
}
return R.error("无法执行");
}
}
package org.springblade.founder.forward.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyClassUtils {
public static List<Class<?>> getClasses(String packageName) {
String path = packageName.replace(".", "/");
List<Class<?>> classes = new ArrayList<>();
String classpath = System.getProperty("java.class.path");
String[] paths = classpath.split(System.getProperty("path.separator"));
for (String classPath : paths) {
File file = new File(classPath + "/" + path);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File childFile : files) {
String fileName = childFile.getName();
if (fileName.endsWith(".class")) {
String className = packageName + "." + fileName.substring(0, fileName.length() - 6);
try {
Class<?> aClass = Class.forName(className);
classes.add(aClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
}
return classes;
}
}
\ No newline at end of file
......@@ -2,29 +2,49 @@ package org.springblade.founder.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.URI;
import java.util.*;
import java.util.Map.Entry;
public class HttpUtil {
private static RequestConfig requestConfig = null;
private static PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager();
private static final Logger logger = Logger.getLogger(HttpUtil.class.getName());
static{
// 设置请求和传输超时时间
//setConnectTimeout:设置连接超时时间,单位毫秒。
//setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
//setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒
requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).build();
}
public static String doGet(String uri) {
HttpClient httpclient = new DefaultHttpClient();
......@@ -72,6 +92,47 @@ public class HttpUtil {
return sb.toString();
}
public static String doGet(String url,Map<String, String> headMap,Map<String, String> param) {
// 创建客户端连接
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null&&param.size()>0) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
httpGet.addHeader(key, headMap.get(key));
}
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断是否请求成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
}
}
return resultString;
}
public static String doGetEsb(String uri, String id) {
HttpClient httpclient = new DefaultHttpClient();
......@@ -336,4 +397,46 @@ public class HttpUtil {
e.printStackTrace();
}
}
/**
* 请求的参数类型为json
* @param url
* @param json
* @return {username:"",pass:""}
*/
public static String doPostJson(String url, Map<String, String> headers, String json) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm).build();
String jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
if(headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
try{
//设置参数解决中文乱码
if (null != json){
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
//发送请求
CloseableHttpResponse result = httpClient.execute(httpPost);
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 读取服务器返回的json数据(然后解析)
jsonResult = EntityUtils.toString(result.getEntity(), "utf-8");
}else{
throw new Exception();
}
}catch (Exception e){
e.printStackTrace();
}finally{
httpPost.releaseConnection();
}
return jsonResult;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment