gpt4 book ai didi

java - 在Java中模拟点击提交按钮

转载 作者:行者123 更新时间:2023-12-02 00:21:22 25 4
gpt4 key购买 nike

我正在用Java编写程序,我想填写表单的指定字段,模拟提交点击,从而得到结果页面。我正在 URL http://stu21.kntu.ac.ir/Login.aspx 上测试我的想法,该 URL 有两个字段 txtusernametxtpassword >。我正在尝试以下代码,但它不会为我返回结果页面。我该怎么做 ?这段代码我做错了什么?

        DefaultHttpClient conn = new DefaultHttpClient();
conn = new DefaultHttpClient();

ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("txtusername", "8810103"));
pairs.add(new BasicNameValuePair("txtpassword", "8810103"));

HttpPost httpPost = new HttpPost("http://stu21.kntu.ac.ir/Login.aspx");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,
"UTF-8");

httpPost.setHeader(
"UserAgent",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.151 Chrome/18.0.1025.151 Safari/535.19");

httpPost.setEntity(entity);
HttpResponse response = conn.execute(httpPost);
InputStream is = response.getEntity().getContent();
RandomAccessFile raf = new RandomAccessFile(
"/home/hossein/Desktop/random.aspx", "rw");
raf.seek(0);

int bytes = 0;
byte[] buffer = new byte[1024];

while ((bytes = is.read(buffer)) != -1)
raf.write(buffer, 0, bytes);

raf.close();
is.close();

抱歉,如果我的问题与其他线程重复,我无法在其他线程上找到我的解决方案。

提前致谢:)

最佳答案

我认为你需要HTTPUnitjavaworld 有一个很好的教程。

看看下面的例子:

public void testGoodLogin() throws Exception {
WebConversation conversation = new WebConversation();
WebRequest request = new GetMethodWebRequest( "http://www.meterware.com/servlet/TopSecret" );
WebResponse response = conversation.getResponse( request );

WebForm loginForm = response.getForms()[0];
request = loginForm.getRequest();
request.setParameter( "name", "master" );

// "clicking the button" programatically
response = conversation.getResponse( request );

assertTrue( "Login not accepted",
response.getText().indexOf( "You made it!" ) != -1 );
assertEquals( "Page title", "Top Secret", response.getTitle() );
}

我相信您可以像这样进行测试。

关于java - 在Java中模拟点击提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10912688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com