使用HttpClient对web应用进行测试

在几天程序突然报出了数据库连接被管理员销毁的情况! 一时之间也毫无头绪, 甚至怀疑我们的程序能否通过压力测试, 所以就使用了HttpClient整了一段测试跑了来测试一下, 最后虽然找到了问题是因为ArcGis占有了很多连接没有释放导致的, 呵呵, 既然写了, 还是拿出来试试:
[code]
package com.gomt.httpclient;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;


public class AutoTest {

static final String LOGON_SITE = "192.168.0.93";
static final int LOGON_PORT = 7001;

public AutoTest() {

}

/**
* @param args
*/
public static void main(String[] args) {
HttpClientFrame f = new HttpClientFrame();
f.setTitle("HttpClient测试");
f.setSize(700, 500);
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.setVisible(true);
}

public static class HttpClientFrame extends JFrame {
private static final long serialVersionUID = 3348783285573305436L;
private JComboBox cmbURL;
private JComboBox runcount;
private JTextField cmbPort;
private JTextArea taTextResponse;
private JEditorPane htmlPane;

private HttpClient client;
String[] userArr = new String[]{"admin", "tianyy", "jiangzy", "caoxd", "changam", "chejh", "chench", "chengh", "chenhr", "guzm", "hesb", "hep", "laijw"};
String[] passArr = new String[]{"admin", "tian", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"};
long begin = 0;

public HttpClientFrame() {

begin = System.currentTimeMillis();
System.out.println("start : " + begin);
//HttpClient
client = new HttpClient(new MultiThreadedHttpConnectionManager());
//client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

JPanel panInput = new JPanel(new FlowLayout());

String[] aURLs = {
"192.168.0.9",
"192.168.0.10",
"192.168.0.93"//,
//"http://www.anybrowser.org/",
//"http://jakarta.apache.org/",
//"http://www.w3.org/"
};

final JButton btnGET = new JButton("测试");
btnGET.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String url = (String) cmbURL.getSelectedItem();
if (url != null && url.length() > 0) {
//loadPage(url);
int runtimes = 1;
int port = 80;
try {
runtimes = Integer.parseInt((String)runcount.getSelectedItem());


} catch(Exception eee) {
runtimes = 1;
}
try {
port = Integer.parseInt(cmbPort.getText());
} catch(Exception ee) {
port = 80;
}

java.util.Random rm = new java.util.Random();
for (int i = 0; i < runtimes; i++) {
int rmi = rm.nextInt();
int arryp = Math.abs(rmi % 13);
System.out.println("arryp = " + arryp);
loadPage(url, i+1, begin, userArr[arryp], passArr[arryp], port);
// PostMethod post = new PostMethod("http://" + url + ":" + LOGON_PORT + "/szsf/loginaction.action");
// NameValuePair username = new NameValuePair("user", userArr[arryp]);
// NameValuePair password = new NameValuePair("pwd", passArr[arryp]);
// NameValuePair method = new NameValuePair("method", "b");
// post.setRequestBody(new NameValuePair[]{username, password, method});
//get.setFollowRedirects(true);

}
}
}
}
);

cmbURL = new JComboBox(aURLs);
cmbURL.setToolTipText("输入一个地址!");
cmbURL.setEditable(true);
cmbURL.setSelectedIndex(0);

cmbPort = new JTextField();
cmbPort.setToolTipText("请输入端口号!");
cmbPort.setEditable(true);
cmbPort.setText("7001");

JLabel lblURL = new JLabel("地址:");

runcount = new JComboBox(new String[]{"1","10","100","1000"});
runcount.setToolTipText("运行次数");
runcount.setEditable(true);
runcount.setSelectedIndex(0);

panInput.add(lblURL);
panInput.add(cmbURL);
panInput.add(cmbPort);
panInput.add(btnGET);
panInput.add(runcount);
panInput.add(new JLabel("次"));

taTextResponse = new JTextArea();
taTextResponse.setEditable(false);
taTextResponse.setCaretPosition(0);

htmlPane = new JEditorPane();
htmlPane.setContentType("text/html;charset=UTF-8");
htmlPane.setEditable(false);

JSplitPane splitResponsePane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(taTextResponse),
new JScrollPane(htmlPane)
);
splitResponsePane.setOneTouchExpandable(false);
splitResponsePane.setDividerLocation(350);
// it would be better to set resizeWeight, but this method does
// not exist in JRE 1.2.2
// splitResponsePane.setResizeWeight(0.5);

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panInput, BorderLayout.NORTH);
this.getContentPane().add(splitResponsePane, BorderLayout.CENTER);
}

/**
* Sets the HTML content to be displayed.
*
* @param content an HTML document
* @throws UnsupportedEncodingException
*/
private void setDocumentContent(String content, InputStream in) throws UnsupportedEncodingException {

HTMLDocument doc = new HTMLDocument();

// try {
// doc.remove(0, doc.getLength());
// } catch (BadLocationException e) {
// e.printStackTrace();
// }
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);

taTextResponse.setText(new String(content.getBytes("GBK"), "UTF-8"));
taTextResponse.setCaretPosition(0);
try {
htmlPane.read(new java.io.ByteArrayInputStream(taTextResponse.getText().getBytes()), doc);
} catch (IOException e) {
e.printStackTrace();
}
if(doc.getLength() != 0) {
htmlPane.setDocument(doc);
htmlPane.setCaretPosition(0);
}
taTextResponse.requestFocus();

}

/**
* Loads the page at the given URL from a separate thread.
* @param url
*/
private void loadPage(final String url, final int id, final long begin,
final String usernames, final String passwords, final int port) {
// create a new thread to load the URL from
new Thread() {
public void run() {
PostMethod post = new PostMethod("http://" + url + ":" + port + "/szsf/loginaction.action");
NameValuePair username = new NameValuePair("user", usernames);
NameValuePair password = new NameValuePair("pwd", passwords);
NameValuePair method = new NameValuePair("method", "b");
post.setRequestBody(new NameValuePair[]{username, password, method});

try {
int iGetResultCode = client.executeMethod(post);
final InputStream in = post.getResponseBodyAsStream();
java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream(5120);
byte[] b = new byte[5120];
int len = 0;
while((len =in.read(b)) > -1) {
byteout.write(b, 0, len);
}

final String strGetResponseBody = new String(byteout.toByteArray());//post.getResponseBodyAsString();
System.out.println("返回状态为:" + iGetResultCode);

if (strGetResponseBody != null) {
// set the HTML on the UI thread
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
try {
setDocumentContent(strGetResponseBody, in);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
post.releaseConnection();
}
}
}.start();
}

}

/**
* A thread that performs a GET.
*/
// static class PostThread extends Thread {
//
// private HttpClient httpClient;
// private PostMethod method;
// private int id;
// private long begin;
//
// public PostThread(HttpClient httpClient, PostMethod method, int id, long begin) {
// this.httpClient = httpClient;
// this.method = method;
// this.id = id;
// this.begin = begin;
//
// }
//
// /**
// * Executes the GetMethod and prints some satus information.
// */
// public void run() {
//
// try {
//
// System.out.println(id + " - about to get something from " + method.getURI());
// // execute the method
// httpClient.executeMethod(method);
//
// //System.out.println(id + " - get executed");
// // get the response body as an array of bytes
// ///byte[] bytes = method.getResponseBody();
//
// //System.out.println(id + " - " + bytes.length + " bytes read");
// final String resString = method.getResponseBodyAsString();
// if (resString != null) {
// // set the HTML on the UI thread
// SwingUtilities.invokeLater(
// new Runnable() {
// public void run() {
// setDocumentContent(resString);
// }
// }
// );
// }
// //System.out.println("返回字串为: " + resString);
//
// } catch (Exception e) {
// System.out.println(id + " - error: " + e);
// } finally {
// // always release the connection after we're done
// method.releaseConnection();
// //System.out.println(id + " - connection released");
// System.out.println(id + " begin: " + begin + " end : "+ System.currentTimeMillis() + " cost : " + (System.currentTimeMillis() - begin)/1000.0);
// }
// }
//
// }

}

[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值