java做https接口测试工具_简单接口测试(http/https),方法已经封装,也写了一个窗口测试工具...

news/2024/7/24 13:13:09 标签: java做https接口测试工具

只要体会最基本的核心代码,什么工具都是卵的,想怎么玩就怎么玩

date:

package Date;

public class User {

private String UserName;

private String PassWord;

public String getUserName() {

return UserName;

}

public String setUserName(String userName) {

return UserName = userName;

}

public String getPassWord() {

return PassWord;

}

public String setPassWord(String passWord) {

return PassWord = passWord;

}

}

窗口测试工具:

login窗口:

package JFrameTool;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.HashMap;

import java.util.Map;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

import Date.User;

import PublicClass.HttpsClass;

public class login extends JFrame {

JTextField jTextField ;     //定义文本框组件

JPasswordField jPasswordField;  //定义密码框组件

JLabel jLabel1,jLabel2;

JPanel jp1,jp2,jp3;

JButton jb1,jb2; //创建按钮

public login() {

jTextField=new JTextField(12);

jPasswordField=new JPasswordField(13);

jLabel1=new JLabel("用户名");

jLabel2 = new JLabel("密码");

jb1 = new JButton("确认");

jb1.addActionListener(new ActionListener() {

//登录监听

@Override

public void actionPerformed(ActionEvent e) {

User user=new User();

String name=jTextField.getText();

String password = jPasswordField.getText();

String user1=user.setUserName(name);

String password1=user.setPassWord(password);

String rs=test(user1,password1);

if(rs!=null){

JOptionPane.showMessageDialog(login.this, "登录成功,登录接口正常");

Main main=new Main();

}else{

JOptionPane.showMessageDialog(login.this, "不存在该用户名");

jTextField.setText("");

jPasswordField.setText("");

}

}

});

jb2 = new JButton("取消");

jp1 = new JPanel();

jp2 = new JPanel();

jp3 = new JPanel();

//设置布局

this.setLayout(new GridLayout(3,1));

jp1.add(jLabel1);

jp1.add(jTextField);//第一块面板添加用户名和文本框

jp2.add(jLabel2);

jp2.add(jPasswordField);//第二块面板添加密码和密码输入框

jp3.add(jb1);

jp3.add(jb2); //第三块面板添加确认和取消

this.add(jp1);

this.add(jp2);

this.add(jp3);  //将三块面板添加到登陆框上面

//设置显示

this.setSize(600, 400);

//this.pack();

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

this.setTitle("登陆");

}

public static void main(String[] args){

new login();

}

public String test(String username,String password) {

String url_login="http://tspdemo.changan.com.cn/appserver/api/user/login";

HttpsClass http=new HttpsClass();

User user=new User();

Map body=new HashMap();

Map headers=new HashMap();

body.put("phone",username);

body.put("password",password);

String result=http.FormPost(url_login, body, headers);

System.out.println(result);

return result;

}

}

主窗口:

package JFrameTool;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.HashMap;

import java.util.Map;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

import Date.User;

import PublicClass.HttpsClass;

public class Main extends JFrame {

JTextField jTextField ;     //定义文本框组件

JPasswordField jPasswordField;  //定义密码框组件

JLabel jLabel1,jLabel2;

JPanel jp1,jp2,jp3;

JButton jb1,jb2; //创建按钮

public Main() {

jTextField=new JTextField(12);

jPasswordField=new JPasswordField(13);

jLabel1=new JLabel("用户名");

jLabel2 = new JLabel("密码");

jb1 = new JButton("确认");

/*jb1.addActionListener(new ActionListener() {

//登录监听

@Override

public void actionPerformed(ActionEvent e) {

User user=new User();

String name=jTextField.getText();

String password = jPasswordField.getText();

String user1=user.setUserName(name);

String password1=user.setPassWord(password);

String rs=test(user1,password1);

if(rs!=null){

JOptionPane.showMessageDialog(login.this, "登录成功,登录接口正常");

}else{

JOptionPane.showMessageDialog(login.this, "不存在该用户名");

jTextField.setText("");

jPasswordField.setText("");

}

}

});*/

jb2 = new JButton("取消");

jp1 = new JPanel();

jp2 = new JPanel();

jp3 = new JPanel();

//设置布局

this.setLayout(new GridLayout(3,1));

jp1.add(jLabel1);

jp1.add(jTextField);//第一块面板添加用户名和文本框

jp2.add(jLabel2);

jp2.add(jPasswordField);//第二块面板添加密码和密码输入框

jp3.add(jb1);

jp3.add(jb2); //第三块面板添加确认和取消

this.add(jp1);

this.add(jp2);

this.add(jp3);  //将三块面板添加到登陆框上面

//设置显示

this.setSize(600, 400);

//this.pack();

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

this.setTitle("登陆");

}

}

调用核心代码封装的方法:

http请求:

package PublicClass;

import java.io.Closeable;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.fluent.Response;

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.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import org.omg.CORBA.portable.RemarshalException;

public class HttpsClass {

/*

* urlEncodeFormEntity实例将会使用URL编码来编码参数

* 生成内容如下:param1=value1&param2=value2

*/

public static String  get(String url,Mapparams) throws IOException {

String result="";

CloseableHttpClient httpClient=null;

HttpGet httpget=null;

try {

// 创建默认的httpClient实例.

httpClient=HttpClients.createDefault();

RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();

String ps="";

//对map的遍历

for(String pKey:params.keySet()){

//根据ps判断是否为空,走if,如果为空,不执行,不为空,执行

if(!"".equals(ps)){

ps=ps+"&";

}

ps=pKey+"="+params.get(pKey);//带参拼凑

}

//拼接url

if(!"".equals(ps)){

url=url+"?"+ps;

}

httpget=new HttpGet(url);

httpget.setConfig(rc);

//调用httpclient响应函数

CloseableHttpResponse response=httpClient.execute(httpget);

HttpEntity httpEntity=response.getEntity();

System.out.print(EntityUtils.toString(httpEntity,"utf-8"));

result=EntityUtils.toString(httpEntity,"utf-8");

result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if(httpget !=null){

httpget.releaseConnection();

}

if(httpClient !=null){

httpClient.close();

}

} catch ( Exception e) {

e.printStackTrace();

}

}

return result;

}

//不带参数的post请求

public static  String LsusbPost(String url,Mapheaers) {

String result="";

CloseableHttpClient httpclient=null;

HttpPost httpPost=null;

try {

httpclient=HttpClients.createDefault();

RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();

httpPost=new HttpPost(url);

httpPost.setConfig(rc);

//创建参数队列

List formparams = new ArrayList();

for(String pKey:heaers.keySet()){

formparams.add(new BasicNameValuePair(pKey, heaers.get(pKey)));

}

httpPost.setEntity(new UrlEncodedFormEntity(formparams));

CloseableHttpResponse response=httpclient.execute(httpPost);

org.apache.http.HttpEntity httpEntity=response.getEntity();

System.out.println(EntityUtils.toString(httpEntity,"utf-8"));

result=EntityUtils.toString(httpEntity,"utf-8");

result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if(httpPost!=null){

httpPost.releaseConnection();

}

if(httpclient!=null){

httpclient.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result;

}

//提交表单post

public static  String FormPost(String url,Mapbody,Mapheaers) {

String result="";

CloseableHttpClient httpclient=null;

HttpPost httpPost=null;

try {

httpclient=HttpClients.createDefault();

RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();

httpPost=new HttpPost(url);

httpPost.setConfig(rc);

httpPost.addHeader("Content-type","application/x-www-form-urlencoded");

for(String pKey:heaers.keySet()){

httpPost.addHeader(pKey, heaers.get(pKey));

}

//创建参数队列

List formparams = new ArrayList();

for(String pKey:body.keySet()){

formparams.add(new BasicNameValuePair(pKey, body.get(pKey)));

}

httpPost.setEntity(new UrlEncodedFormEntity(formparams));

CloseableHttpResponse response=httpclient.execute(httpPost);

org.apache.http.HttpEntity httpEntity=response.getEntity();

//System.out.println(EntityUtils.toString(httpEntity,"utf-8"));

//EntityUtils.toString只能用一次,否则抛异常

result=EntityUtils.toString(httpEntity,"utf-8");

result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if(httpPost!=null){

httpPost.releaseConnection();

}

if(httpclient!=null){

httpclient.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result;

}

}

https函数封装:

package PublicClass;

import java.io.IOException;

import java.security.GeneralSecurityException;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLException;

import javax.net.ssl.SSLSession;

import javax.net.ssl.SSLSocket;

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.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.conn.ssl.TrustStrategy;

import org.apache.http.conn.ssl.X509HostnameVerifier;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.ssl.SSLContextBuilder;

import org.apache.http.util.EntityUtils;

public class HttpClass {

private static PoolingHttpClientConnectionManager connMgr;

private static RequestConfig requestConfig;

private static final int MAX_TIMEOUT = 7000;

static {

// 设置连接池

connMgr = new PoolingHttpClientConnectionManager();

// 设置连接池大小

connMgr.setMaxTotal(100);

connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

RequestConfig.Builder configBuilder = RequestConfig.custom();

// 设置连接超时

configBuilder.setConnectTimeout(MAX_TIMEOUT);

// 设置读取超时

configBuilder.setSocketTimeout(MAX_TIMEOUT);

// 设置从连接池获取连接实例的超时

configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

// 在提交请求之前 测试连接是否可用

configBuilder.setStaleConnectionCheckEnabled(true);

requestConfig = configBuilder.build();

}

public String PostSSL(String url,Mapheader){

String result="";

CloseableHttpClient httpClient=null;

HttpPost httpPost=null;

try {

httpClient = HttpClients.custom().

setSSLSocketFactory(createSSLConnSocketFactory()).

setConnectionManager(connMgr).

setDefaultRequestConfig(requestConfig).build();

RequestConfig rc=RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();

httpPost=new HttpPost(url);

httpPost.setConfig(rc);

//创建参数队列

List formparams = new ArrayList();

for(String pKey:header.keySet()){

formparams.add(new BasicNameValuePair(pKey, header.get(pKey)));

}

httpPost.setEntity(new UrlEncodedFormEntity(formparams));

CloseableHttpResponse response=httpClient.execute(httpPost);

org.apache.http.HttpEntity httpEntity=response.getEntity();

System.out.println(EntityUtils.toString(httpEntity,"utf-8"));

result=EntityUtils.toString(httpEntity,"utf-8");

result="status="+response.getStatusLine().getStatusCode()+"&&"+"body="+result;

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally {

try {

if(httpPost!=null){

httpPost.releaseConnection();

}

if(httpClient!=null){

httpClient.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result;

}

/**

* 创建SSL安全连接

*

* @return

*/

private static SSLConnectionSocketFactory createSSLConnSocketFactory() {

SSLConnectionSocketFactory sslsf = null;

try {

SSLContext sslContext = new SSLContextBuilder().

loadTrustMaterial(null, new TrustStrategy() {

public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {

return true;

}

}).build();

sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

public boolean verify(String arg0, SSLSession arg1) {

return true;

}

public void verify(String host, SSLSocket ssl) throws IOException {

}

public void verify(String host, X509Certificate cert) throws SSLException {

}

public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {

}

});

} catch (GeneralSecurityException e) {

e.printStackTrace();

}

return sslsf;

}

a04929bc2f67734cd0bb4bfd9ab28b00.png

结果如下,点击确定会跳转窗口

}

0a9671aa6f20f3aa7616a078e673e904.png

总结:把核心的http和https封装成方法,运用到工具中,想怎么用就怎么用


http://www.niftyadmin.cn/n/1519087.html

相关文章

java自签名程序_如何让一台机器信任一个自签名的Java应用程序

如何让一台机器信任一个自签名的Java应用程序我正在部署一个使用JAWS的应用程序,直到2013年底,当我收到警告,它才工作,然后今天早上Java完全封锁了它。 法文的信息是:应用bloquepar lesparamtresdescuritJava应用程序自…

24.RocketMQ之动态增减NameServer

highlight: arduino-light 动态增减NameServer 一个消息队列集群由多台机器组成,持续稳定地提供服务,因为业务需求或硬件故障,经常需要增加或减少各个角色的机器,本节介绍如何在不影响服务稳定性的情况下动态地增减机器。 NameSer…

解决一直弹出 git-credential-oskeychain 的问题

欢迎关注微信公众号:【 全栈攻略 】 1.先使用命令下载 git-credential-osxkeychain curl http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain -o git-credential-osxkeychain2.把 git-credential-osxkeychain 放入 bin目录 mv git-…

java可以操作扫描仪吗_在Java中操作扫描仪(使用JNI)

在Java中操作扫描仪(使用JNI)作者: 文章来源:发布日期:2005年01月01日 浏览次数:1次这是一个用java来操作扫描仪的小例子:package edu.ctgu.JTwacker;import java.awt.BorderLayout;import java.awt.Cursor;impo…

小程序上线发布后,实现版本自动更新,用户无感知

欢迎关注微信公众号:【 全栈攻略 】 直接上代码,用的都是小程序的API。 /*** 检测当前的小程序是否是最新版本,判断是否需要下载、更新当前小程序*/ function checkUpdateVersion() {//判断小程序版本是否可以使用小程序更新机制APIif (wx.…

java 文本框获取焦点 showopendialog冲突_JFileChooser.showOpenDialog没有打开,并且没有抛出错误?...

好吧,我试着做一个十六进制编辑器,我试着做一个加载JMenuItem,但它不起作用。JFileChooser打开对话框没有显示,也没有显示错误。import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;import java.util.Vector;imp…

为数组新增一个flat方法(浏览器不支持的话),可以将一个数组打平,并支持传入最深的层级数,得到打平对应层级的新数组

例如:[1, [2, 3, [4, 5, [6, 7], 8]], 9].flat(2) 得到 [1, 2, 3, 4, 5,[ 6, 7],8,9] 直接上代码: Array.prototype.flat function (dep 1) {return this.reduce((acc, val) > {return acc.concat(Array.isArray(val) && dep > 0 ? va…

php mysql 并发查询_PHP并发查询MySQL的实例代码

最近在研究PHP,很喜欢,碰到PHP并发查询MySQL的问题,研究了一下,顺便留个笔记:同步查询这是我们最常的调用模式,客户端调用Query[函数],发起查询命令,等待结果返回,读取结…