简单接口测试(http/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<String, String> body=new HashMap<String, String>();
Map<String, String> headers=new HashMap<String, String>();
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,Map<String,String>params) 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,Map<String, String>heaers) {
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<NameValuePair> formparams = new ArrayList<NameValuePair>();
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,Map<String, String>body,Map<String, String>heaers) {
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<NameValuePair> formparams = new ArrayList<NameValuePair>();
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,Map<String, String>header){
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<NameValuePair> formparams = new ArrayList<NameValuePair>();
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;  
    } 

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

结果如下,点击确定会跳转窗口
}简单接口测试(http/https),方法已经封装,也写了一个窗口测试工具







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