Merge branch 'master' into registry-nacos

pull/1/head
tanghc 5 years ago
commit 7a7a3b7c8c
  1. 11
      sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/FormBodyWrapperFilterExt.java
  2. 11
      sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/Servlet30WrapperFilterExt.java
  3. 4
      sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenRequest.java
  4. 31
      sop-test/pom.xml
  5. 13
      sop-test/src/main/java/com/gitee/sop/App.java
  6. 381
      sop-test/src/main/java/com/gitee/sop/test/HttpTool.java
  7. 2
      sop-test/src/main/java/com/gitee/sop/test/alipay/AlipayApiException.java
  8. 2
      sop-test/src/main/java/com/gitee/sop/test/alipay/AlipayConstants.java
  9. 2
      sop-test/src/main/java/com/gitee/sop/test/alipay/AlipaySignature.java
  10. 2
      sop-test/src/main/java/com/gitee/sop/test/alipay/StreamUtil.java
  11. 2
      sop-test/src/main/java/com/gitee/sop/test/alipay/StringUtils.java
  12. 2
      sop-test/src/main/java/com/gitee/sop/test/taobao/Constants.java
  13. 4
      sop-test/src/main/java/com/gitee/sop/test/taobao/TaobaoSignature.java
  14. 145
      sop-test/src/test/java/com/gitee/sop/TestBase.java
  15. 6
      sop-test/src/test/java/com/gitee/sop/test/AlipayClientPostTest.java
  16. 4
      sop-test/src/test/java/com/gitee/sop/test/DubboDemoTest.java
  17. 3
      sop-test/src/test/java/com/gitee/sop/test/EasyopenClientPostTest.java
  18. 4
      sop-test/src/test/java/com/gitee/sop/test/JSR303DemoTest.java
  19. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest.java
  20. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest2.java
  21. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest3.java
  22. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest4.java
  23. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest5.java
  24. 4
      sop-test/src/test/java/com/gitee/sop/test/LimitDemoPostTest6.java
  25. 6
      sop-test/src/test/java/com/gitee/sop/test/LoadBalanceTest.java
  26. 4
      sop-test/src/test/java/com/gitee/sop/test/PermissionDemoPostTest.java
  27. 4
      sop-test/src/test/java/com/gitee/sop/test/RestUrlTest.java
  28. 4
      sop-test/src/test/java/com/gitee/sop/test/SpringCloudGatewayClientPostTest.java
  29. 4
      sop-test/src/test/java/com/gitee/sop/test/SpringmvcDemoPostTest.java
  30. 4
      sop-test/src/test/java/com/gitee/sop/test/StoryDemoTest.java
  31. 5
      sop-test/src/test/java/com/gitee/sop/test/TaobaoClientPostTest.java
  32. 53
      sop-test/src/test/java/com/gitee/sop/test/TestBase.java
  33. 4
      sop-test/src/test/java/com/gitee/sop/test/ThrowExceptionDemoTest.java
  34. 164
      sop-website/website-server/src/main/java/com/gitee/sop/websiteserver/bean/HttpTool.java
  35. 60
      sop-website/website-server/src/main/java/com/gitee/sop/websiteserver/bean/UploadFile.java
  36. 5
      sop-website/website-server/src/main/java/com/gitee/sop/websiteserver/controller/SandboxController.java
  37. 65
      sop-website/website-server/src/main/java/com/gitee/sop/websiteserver/util/FileUtil.java

@ -11,15 +11,4 @@ public class FormBodyWrapperFilterExt extends FormBodyWrapperFilter {
return BaseZuulFilter.FORM_BODY_WRAPPER_FILTER_ORDER; return BaseZuulFilter.FORM_BODY_WRAPPER_FILTER_ORDER;
} }
// @Override
// public boolean shouldFilter() {
// RequestContext ctx = RequestContext.getCurrentContext();
// HttpServletRequest request = ctx.getRequest();
// // 如果是文件上传请求,不需要包装
// if (RequestUtil.isMultipart(request)) {
// return false;
// } else {
// return super.shouldFilter();
// }
// }
} }

@ -11,15 +11,4 @@ public class Servlet30WrapperFilterExt extends Servlet30WrapperFilter {
return BaseZuulFilter.SERVLET_30_WRAPPER_FILTER_ORDER; return BaseZuulFilter.SERVLET_30_WRAPPER_FILTER_ORDER;
} }
// @Override
// public boolean shouldFilter() {
// RequestContext ctx = RequestContext.getCurrentContext();
// HttpServletRequest request = ctx.getRequest();
// // 如果是文件上传请求,不需要包装
// if (RequestUtil.isMultipart(request)) {
// return false;
// } else {
// return super.shouldFilter();
// }
// }
} }

@ -42,9 +42,7 @@ public class OpenRequest {
} }
return openHttp.get(url, header); return openHttp.get(url, header);
} else { } else {
return openHttp.request(url, form, header, requestMethod.name()); return openHttp.requestJson(url, JSON.toJSONString(form), header);
// 下面这种方式也可以,以application/json方式请求
// return openHttp.requestJson(url, JSON.toJSONString(form), header);
} }
} }
} catch (IOException e) { } catch (IOException e) {

@ -12,8 +12,6 @@
<artifactId>sop-test</artifactId> <artifactId>sop-test</artifactId>
<name>sop-test</name> <name>sop-test</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -23,28 +21,20 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>junit</artifactId> <artifactId>okhttp</artifactId>
<version>4.11</version> <version>3.14.0</version>
<scope>test</scope> <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.5</version> <version>2.5</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.58</version> <version>1.2.58</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -52,6 +42,19 @@
<version>1.11</version> <version>1.11</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -1,13 +0,0 @@
package com.gitee.sop;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

@ -0,0 +1,381 @@
package com.gitee.sop.test;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* http请求工具基于OKHTTP3
* @author tanghc
*/
public class HttpTool {
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private Map<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
private OkHttpClient httpClient;
public HttpTool() {
this(new HttpToolConfig());
}
public HttpTool(HttpToolConfig httpToolConfig) {
this.initHttpClient(httpToolConfig);
}
protected void initHttpClient(HttpToolConfig httpToolConfig) {
httpClient = new OkHttpClient.Builder()
.connectTimeout(httpToolConfig.connectTimeoutSeconds, TimeUnit.SECONDS) // 设置链接超时时间,默认10秒
.readTimeout(httpToolConfig.readTimeoutSeconds, TimeUnit.SECONDS)
.writeTimeout(httpToolConfig.writeTimeoutSeconds, TimeUnit.SECONDS)
.cookieJar(new CookieJar() {
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl.host(), list);
}
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
}
@Data
public static class HttpToolConfig {
/**
* 请求超时时间
*/
private int connectTimeoutSeconds = 10;
/**
* http读取超时时间
*/
private int readTimeoutSeconds = 10;
/**
* http写超时时间
*/
private int writeTimeoutSeconds = 10;
}
/**
* get请求
*
* @param url
* @param header
* @return
* @throws IOException
*/
public String get(String url, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder().url(url).get();
// 添加header
addHeader(builder, header);
Request request = builder.build();
Response response = httpClient.newCall(request).execute();
return response.body().string();
}
/**
* 提交表单
*
* @param url url
* @param form 参数
* @param header header
* @param method 请求方式postget等
* @return
* @throws IOException
*/
public String request(String url, Map<String, String> form, Map<String, String> header, HTTPMethod method) throws IOException {
Request.Builder requestBuilder = buildRequestBuilder(url, form, method.value());
// 添加header
addHeader(requestBuilder, header);
Request request = requestBuilder.build();
Response response = httpClient
.newCall(request)
.execute();
try {
return response.body().string();
} finally {
response.close();
}
}
/**
* 请求json数据contentType=application/json
* @param url 请求路径
* @param json json数据
* @param header header
* @return 返回响应结果
* @throws IOException
*/
public String requestJson(String url, String json, Map<String, String> header) throws IOException {
RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.post(body);
// 添加header
addHeader(requestBuilder, header);
Request request = requestBuilder.build();
Response response = httpClient
.newCall(request)
.execute();
try {
return response.body().string();
} finally {
response.close();
}
}
public static Request.Builder buildRequestBuilder(String url, Map<String, String> form, String method) {
switch (method) {
case "get":
return new Request.Builder()
.url(buildHttpUrl(url, form))
.get();
case "head":
return new Request.Builder()
.url(buildHttpUrl(url, form))
.head();
case "put":
return new Request.Builder()
.url(url)
.put(buildFormBody(form));
case "delete":
return new Request.Builder()
.url(url)
.delete(buildFormBody(form));
default:
return new Request.Builder()
.url(url)
.post(buildFormBody(form));
}
}
public static HttpUrl buildHttpUrl(String url, Map<String, String> form) {
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
for (Map.Entry<String, String> entry : form.entrySet()) {
urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
}
return urlBuilder.build();
}
public static FormBody buildFormBody(Map<String, String> form) {
FormBody.Builder paramBuilder = new FormBody.Builder(StandardCharsets.UTF_8);
for (Map.Entry<String, String> entry : form.entrySet()) {
paramBuilder.add(entry.getKey(), entry.getValue());
}
return paramBuilder.build();
}
/**
* 提交表单并且上传文件
*
* @param url
* @param form
* @param header
* @param files
* @return
* @throws IOException
*/
public String requestFile(String url, Map<String, String> form, Map<String, String> header, List<UploadFile> files)
throws IOException {
// 创建MultipartBody.Builder,用于添加请求的数据
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
bodyBuilder.setType(MultipartBody.FORM);
for (UploadFile uploadFile : files) {
bodyBuilder.addFormDataPart(uploadFile.getName(), // 请求的名字
uploadFile.getFileName(), // 文件的文字,服务器端用来解析的
RequestBody.create(null, uploadFile.getFileData()) // 创建RequestBody,把上传的文件放入
);
}
Set<Map.Entry<String, String>> entrySet = form.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
bodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
RequestBody requestBody = bodyBuilder.build();
Request.Builder builder = new Request.Builder().url(url).post(requestBody);
// 添加header
addHeader(builder, header);
Request request = builder.build();
Response response = httpClient.newCall(request).execute();
try {
return response.body().string();
} finally {
response.close();
}
}
private void addHeader(Request.Builder builder, Map<String, String> header) {
if (header != null) {
Set<Map.Entry<String, String>> entrySet = header.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
builder.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
}
public void setCookieStore(Map<String, List<Cookie>> cookieStore) {
this.cookieStore = cookieStore;
}
public void setHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
}
public enum HTTPMethod {
GET,
POST,
PUT,
HEAD,
DELETE;
private HTTPMethod() {
}
public String value() {
return this.name();
}
public static HTTPMethod fromValue(String v) {
return valueOf(v);
}
}
/**
* 文件上传类
* @author tanghc
*/
@Getter
@Setter
public static class UploadFile implements Serializable {
private static final long serialVersionUID = -1100614660944996398L;
/**
* @param name 表单名称不能重复
* @param file 文件
* @throws IOException
*/
public UploadFile(String name, File file) throws IOException {
this(name, file.getName(), FileUtil.toBytes(file));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param input 文件流
* @throws IOException
*/
public UploadFile(String name, String fileName, InputStream input) throws IOException {
this(name, fileName, FileUtil.toBytes(input));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param fileData 文件数据
*/
public UploadFile(String name, String fileName, byte[] fileData) {
super();
this.name = name;
this.fileName = fileName;
this.fileData = fileData;
this.md5 = DigestUtils.md5Hex(fileData);
}
private String name;
private String fileName;
private byte[] fileData;
private String md5;
}
public static class FileUtil {
/**
* The default buffer size to use.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final int EOF = -1;
/**
* 将文件流转换成byte[]
* @param input
* @return
* @throws IOException
*/
public static byte[] toBytes(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
int n = 0;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 将文件转换成数据流
* @param file 文件
* @return 返回数据流
* @throws IOException
*/
public static byte[] toBytes(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
InputStream input = null;
try {
input = new FileInputStream(file);
return toBytes(input);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
}
}
}
}
}

@ -2,7 +2,7 @@
* Alipay.com Inc. * Alipay.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved. * Copyright (c) 2004-2012 All Rights Reserved.
*/ */
package com.gitee.sop.alipay; package com.gitee.sop.test.alipay;
/** /**

@ -2,7 +2,7 @@
* Alipay.com Inc. * Alipay.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved. * Copyright (c) 2004-2012 All Rights Reserved.
*/ */
package com.gitee.sop.alipay; package com.gitee.sop.test.alipay;
/** /**
* *

@ -2,7 +2,7 @@
* Alipay.com Inc. * Alipay.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved. * Copyright (c) 2004-2012 All Rights Reserved.
*/ */
package com.gitee.sop.alipay; package com.gitee.sop.test.alipay;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;

@ -2,7 +2,7 @@
* Alipay.com Inc. * Alipay.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved. * Copyright (c) 2004-2012 All Rights Reserved.
*/ */
package com.gitee.sop.alipay; package com.gitee.sop.test.alipay;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;

@ -1,4 +1,4 @@
package com.gitee.sop.alipay; package com.gitee.sop.test.alipay;
/** /**
* 字符串工具类 * 字符串工具类

@ -1,4 +1,4 @@
package com.gitee.sop.taobao; package com.gitee.sop.test.taobao;
/** /**
* @author tanghc * @author tanghc

@ -1,6 +1,6 @@
package com.gitee.sop.taobao; package com.gitee.sop.test.taobao;
import com.gitee.sop.alipay.StringUtils; import com.gitee.sop.test.alipay.StringUtils;
import javax.crypto.Mac; import javax.crypto.Mac;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;

@ -1,145 +0,0 @@
package com.gitee.sop;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author tanghc
*/
public class TestBase extends TestCase {
/**
* 发送POST请求
* @param url
* @return JSON或者字符串
* @throws Exception
*/
public static String post(String url, Map<String, String> params) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
/**
* 创建一个httpclient对象
*/
client = HttpClients.createDefault();
/**
* 创建一个post对象
*/
HttpPost post = new HttpPost(url);
List<NameValuePair> nameValuePairs = params.entrySet().stream().map(entry -> {
return new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
}).collect(Collectors.toList());
/**
* 包装成一个Entity对象
*/
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
/**
* 设置请求的内容
*/
post.setEntity(entity);
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
/**
* 执行post请求
*/
response = client.execute(post);
/**
* 通过EntityUitls获取返回内容
*/
// Header[] allHeaders = response.getAllHeaders();
// if (allHeaders != null && allHeaders.length > 0) {
// System.out.println("----------- headers -----------");
// for (Header allHeader : allHeaders) {
// System.out.println(allHeader);
// }
// }
return EntityUtils.toString(response.getEntity(),"UTF-8");
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(client);
IOUtils.closeQuietly(response);
}
return null;
}
/**
* 发送get请求
* @param url
* @return JSON或者字符串
* @throws Exception
*/
public static String get(String url, Map<String, String> params) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
/**
* 创建一个httpclient对象
*/
client = HttpClients.createDefault();
List<NameValuePair> nameValuePairs = params.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())))
.collect(Collectors.toList());
/**
* 包装成一个Entity对象
*/
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
//参数转换为字符串
String paramsStr = EntityUtils.toString(entity);
url = url + "?" + paramsStr;
/**
* 创建一个post对象
*/
HttpGet get = new HttpGet(url);
/**
* 执行post请求
*/
response = client.execute(get);
/**
* 通过EntityUitls获取返回内容
*/
// Header[] allHeaders = response.getAllHeaders();
// if (allHeaders != null && allHeaders.length > 0) {
// System.out.println("----------- headers -----------");
// for (Header allHeader : allHeaders) {
// System.out.println(allHeader);
// }
// }
return EntityUtils.toString(response.getEntity(),"UTF-8");
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(client);
IOUtils.closeQuietly(response);
}
return null;
}
protected String buildParamQuery(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString().substring(1);
}
}

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -34,7 +34,7 @@ public class AlipayClientPostTest extends TestBase {
*/ */
// 这个请求会路由到story服务 // 这个请求会路由到story服务
@Test @Test
public void testPost() throws Exception { public void testGet() throws Exception {
// 公共请求参数 // 公共请求参数
Map<String, String> params = new HashMap<String, String>(); Map<String, String> params = new HashMap<String, String>();

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,6 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import junit.framework.TestCase;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test; import org.junit.Test;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,8 +1,8 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipayApiException; import com.gitee.sop.test.alipay.AlipayApiException;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,7 +1,6 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.gitee.sop.test.taobao.TaobaoSignature;
import com.gitee.sop.taobao.TaobaoSignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -0,0 +1,53 @@
package com.gitee.sop.test;
import com.alibaba.fastjson.JSON;
import junit.framework.TestCase;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
/**
* @author tanghc
*/
public class TestBase extends TestCase {
static HttpTool httpTool = new HttpTool();
/**
* 发送POST请求
*
* @param url
* @return JSON或者字符串
*/
public static String post(String url, Map<String, String> params) {
try {
return httpTool.requestJson(url, JSON.toJSONString(params), Collections.emptyMap());
} catch (IOException e) {
throw new RuntimeException("网络请求异常", e);
}
}
/**
* 发送get请求
*
* @param url
* @return JSON或者字符串
*/
public static String get(String url, Map<String, String> params) {
try {
return httpTool.request(url, params, Collections.emptyMap(), HttpTool.HTTPMethod.GET);
} catch (IOException e) {
throw new RuntimeException("网络请求异常", e);
}
}
protected static String buildParamQuery(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString().substring(1);
}
}

@ -1,7 +1,7 @@
package com.gitee.sop; package com.gitee.sop.test;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.gitee.sop.alipay.AlipaySignature; import com.gitee.sop.test.alipay.AlipaySignature;
import org.junit.Test; import org.junit.Test;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

@ -1,17 +1,27 @@
package com.gitee.sop.websiteserver.bean; package com.gitee.sop.websiteserver.bean;
import lombok.Data; import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import okhttp3.Cookie; import okhttp3.Cookie;
import okhttp3.CookieJar; import okhttp3.CookieJar;
import okhttp3.FormBody; import okhttp3.FormBody;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody; import okhttp3.MultipartBody;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -21,9 +31,12 @@ import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* http请求工具基于OKHTTP3
* @author tanghc * @author tanghc
*/ */
public class HttpTool { public class HttpTool {
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private Map<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>(); private Map<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
private OkHttpClient httpClient; private OkHttpClient httpClient;
@ -97,8 +110,35 @@ public class HttpTool {
* @return * @return
* @throws IOException * @throws IOException
*/ */
public String request(String url, Map<String, String> form, Map<String, String> header, String method) throws IOException { public String request(String url, Map<String, String> form, Map<String, String> header, HTTPMethod method) throws IOException {
Request.Builder requestBuilder = buildRequestBuilder(url, form, method); Request.Builder requestBuilder = buildRequestBuilder(url, form, method.value());
// 添加header
addHeader(requestBuilder, header);
Request request = requestBuilder.build();
Response response = httpClient
.newCall(request)
.execute();
try {
return response.body().string();
} finally {
response.close();
}
}
/**
* 请求json数据contentType=application/json
* @param url 请求路径
* @param json json数据
* @param header header
* @return 返回响应结果
* @throws IOException
*/
public String requestJson(String url, String json, Map<String, String> header) throws IOException {
RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.post(body);
// 添加header // 添加header
addHeader(requestBuilder, header); addHeader(requestBuilder, header);
@ -215,4 +255,124 @@ public class HttpTool {
this.httpClient = httpClient; this.httpClient = httpClient;
} }
public enum HTTPMethod {
GET,
POST,
PUT,
HEAD,
DELETE;
public String value() {
return this.name();
}
public static HTTPMethod fromValue(String v) {
return valueOf(v.toUpperCase());
}
}
/**
* 文件上传类
* @author tanghc
*/
@Getter
@Setter
public static class UploadFile implements Serializable {
private static final long serialVersionUID = -1100614660944996398L;
/**
* @param name 表单名称不能重复
* @param file 文件
* @throws IOException
*/
public UploadFile(String name, File file) throws IOException {
this(name, file.getName(), FileUtil.toBytes(file));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param input 文件流
* @throws IOException
*/
public UploadFile(String name, String fileName, InputStream input) throws IOException {
this(name, fileName, FileUtil.toBytes(input));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param fileData 文件数据
*/
public UploadFile(String name, String fileName, byte[] fileData) {
super();
this.name = name;
this.fileName = fileName;
this.fileData = fileData;
this.md5 = DigestUtils.md5Hex(fileData);
}
private String name;
private String fileName;
private byte[] fileData;
private String md5;
}
public static class FileUtil {
/**
* The default buffer size to use.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final int EOF = -1;
/**
* 将文件流转换成byte[]
* @param input
* @return
* @throws IOException
*/
public static byte[] toBytes(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
int n = 0;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 将文件转换成数据流
* @param file 文件
* @return 返回数据流
* @throws IOException
*/
public static byte[] toBytes(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
InputStream input = null;
try {
input = new FileInputStream(file);
return toBytes(input);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
}
}
}
}
} }

@ -1,60 +0,0 @@
package com.gitee.sop.websiteserver.bean;
import com.gitee.sop.websiteserver.util.FileUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
/**
* 文件上传类
* @author tanghc
*/
@Getter
@Setter
public class UploadFile implements Serializable {
private static final long serialVersionUID = -1100614660944996398L;
/**
* @param name 表单名称不能重复
* @param file 文件
* @throws IOException
*/
public UploadFile(String name, File file) throws IOException {
this(name, file.getName(), FileUtil.toBytes(file));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param input 文件流
* @throws IOException
*/
public UploadFile(String name, String fileName, InputStream input) throws IOException {
this(name, fileName, FileUtil.toBytes(input));
}
/**
* @param name 表单名称不能重复
* @param fileName 文件名
* @param fileData 文件数据
*/
public UploadFile(String name, String fileName, byte[] fileData) {
super();
this.name = name;
this.fileName = fileName;
this.fileData = fileData;
this.md5 = DigestUtils.md5Hex(fileData);
}
private String name;
private String fileName;
private byte[] fileData;
private String md5;
}

@ -1,7 +1,7 @@
package com.gitee.sop.websiteserver.controller; package com.gitee.sop.websiteserver.controller;
import com.gitee.sop.websiteserver.bean.HttpTool; import com.gitee.sop.websiteserver.bean.HttpTool;
import com.gitee.sop.websiteserver.bean.UploadFile; import com.gitee.sop.websiteserver.bean.HttpTool.*;
import com.gitee.sop.websiteserver.sign.AlipayApiException; import com.gitee.sop.websiteserver.sign.AlipayApiException;
import com.gitee.sop.websiteserver.sign.AlipaySignature; import com.gitee.sop.websiteserver.sign.AlipaySignature;
import com.gitee.sop.websiteserver.util.UploadUtil; import com.gitee.sop.websiteserver.util.UploadUtil;
@ -37,6 +37,7 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* 沙箱环境代理类 * 沙箱环境代理类
* @author tanghc * @author tanghc
@ -113,7 +114,7 @@ public class SandboxController {
if (!CollectionUtils.isEmpty(files)) { if (!CollectionUtils.isEmpty(files)) {
responseData = httpTool.requestFile(url, params, Collections.emptyMap(), files); responseData = httpTool.requestFile(url, params, Collections.emptyMap(), files);
} else { } else {
responseData = httpTool.request(url, params, Collections.emptyMap(), httpMethod); responseData = httpTool.request(url, params, Collections.emptyMap(), HTTPMethod.fromValue(httpMethod));
} }
result.apiResult = responseData; result.apiResult = responseData;
return result; return result;

@ -1,65 +0,0 @@
package com.gitee.sop.websiteserver.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class FileUtil {
/**
* The default buffer size to use.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final int EOF = -1;
/**
* 将文件流转换成byte[]
* @param input
* @return
* @throws IOException
*/
public static byte[] toBytes(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
int n = 0;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 将文件转换成数据流
* @param file 文件
* @return 返回数据流
* @throws IOException
*/
public static byte[] toBytes(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
InputStream input = null;
try {
input = new FileInputStream(file);
return toBytes(input);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
}
}
}
}
Loading…
Cancel
Save