创建HTTPS Mock Server
前言
在开发阶段无法跟实际第三方系统服务器端交互,或者第三方服务器端没有提供测试环境时,测试人员需要提供一个模拟的服务器端,本文提供了mock server的代码,且提供客户端连接时绕开证书校验步骤(即客户端用https连接前,无需导入证书)。
代码
文件读写(非必须,保存请求json用)
文件读写代码片
.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
public class MyFile {
// 使用BufferedReader / BufferedWriter
public void write(File file, StringBuffer sb) {
try {
if (!file.exists())
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(sb.toString());
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public StringBuffer read(File file) {
StringBuffer content = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
content.append(line + "\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
//使用 InputStream / OutputStream 读写
public StringBuffer readFile1(String path) {
try {
InputStream in = new FileInputStream(path);
byte[] data = new byte[in.available()];
in.read(data);
in.close();
return new StringBuffer(new String(data));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void writeFile1(String path, StringBuffer sb) {
try {
OutputStream out = new FileOutputStream(path);
out.write(sb.toString().getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//使用 FileWriter / FileReader 读写文件
public StringBuffer readFile2(String path) {
File f = new File(path);
try {
FileReader fr = new FileReader(f);
char[] cbuf = new char[(int) f.length()];
fr.read(cbuf);
fr.close();
// return new String(cbuf);
StringBuffer sb = new StringBuffer();
for (char c:cbuf)
sb.append(c);
return sb;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void writeFile2(String path, StringBuffer sb) {
File f = new File(path);
try {
FileWriter fw = new FileWriter(f);
fw.write(sb.toString());
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
HTTP客户端操作(绕过客户端证书校验)
代码片
.
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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 com.alibaba.fastjson.JSONObject;
import com.duliday.utils.MyFile;
public class SSLClient {
private static Logger logger = LoggerFactory.getLogger(SSLClient.class);
//绕过ssl认证
public HttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
return httpclient;
} catch (Exception e) {
return HttpClients.createDefault();
}
}
public JSONObject post(CloseableHttpClient httpclient, String url, String body) {
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
StringEntity postingString = new StringEntity(body, "utf-8");
post.setEntity(postingString);
post.setHeader("Content-Type", "application/json");
response = httpclient.execute(post);
String result = EntityUtils.toString(response.getEntity());
JSONObject js = JSONObject.parseObject(result);
return js;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
SSLClient https = new SSLClient();
CloseableHttpClient httpclient = null;
MyFile fil = new MyFile();
httpclient = (CloseableHttpClient) https.wrapClient();
String url = "https://localhost:16790";
//请求的json内容在文件中
String body = fil.readFile1("C:\\work\\myproj\\demo\\request.txt").toString();
JSONObject js = https.post(httpclient, url, body);
logger.info("get Response: " + js.get("response").toString());
}
}
模拟HTTPS 服务器端
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import com.test.duliday.util.MyConst;
import com.test.duliday.util.MyLogger;
public class MyHttpsServer {
private static SSLContext getSslContext() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
String KEYSTORE_FILE = "C:\\src\\myserv_ks";
String KEYSTORE_PASSWORD = "123456";
String KEY_PASSWORD = "123456";
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, KEY_PASSWORD.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS"); //SSLv3, TLS
// sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext;
}
public static void main(String[] args) {
HttpServerProvider provider = HttpServerProvider.provider();
// HttpServer server =provider.createHttpServer(new InetSocketAddress(8082), 0);//监听端口8082
try {
// HttpsServer server = provider.createHttpsServer(new InetSocketAddress(16790), 0);
HttpsServer server = HttpsServer.create(new InetSocketAddress(InetAddress.getByName("localhost"), 16790), 0);
SSLContext sslContext;
sslContext = MyHttpsServer.getSslContext();
server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
MyHttpHandler handler = new MyHttpHandler();
server.createContext("/", handler);
RechargeHandler recharge = new RechargeHandler();
server.createContext("/recharge", recharge);
server.setExecutor(null);
server.start();
MyConst.log = MyLogger.getMylog();
MyConst.log.info("fakeserver server started");
} catch (Exception e) {
MyConst.log.info("Failed to start fakeserver server:\n" + e);
e.printStackTrace();
}
}
}
MyHttpHandler请求处理
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.test.duliday.util.MyConst;
import com.test.duliday.util.MyJSON;
import com.test.duliday.util.MyRedis;
import com.test.duliday.util.MyString;
import com.test.duliday.util.ReturnObject;
public class MyHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
InputStream is = exchange.getRequestBody();
String response = "";
//这里处理https请求,代码略
is.close();
Headers headers = exchange.getResponseHeaders();
headers.set("Content-Type", "application/json; charset=utf-8");
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
headers.set("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");
headers.set("Content-Type", "application/x-www-form-urlencoded");
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
运行
- 打包<MyHttpsServer.java> 和<MyHttpHandler.java> 为<fakeserver.jar>
- 启动服务 <MyHttpsServer.class>文件: java -jar fakeserver.jar
- 运行<SSLClient.java>