java - 使用 HTTPURLConnection 提交表单

标签 java httpurlconnection

您好,我正在尝试使用 HTTPURLConnection 提交以下表单作为练习。

<form name="popnames" method="post" action="/cgi-bin/popularnames.cgi" onsubmit="return       submitIt();">
<p>
<label for="year">Birth Year:</label><br>
<input type="text" name="year" size="5" maxlength="4" id="year" value="2011">
</p>
<p>
<label for="rank">Popularity:</label><br>
<select name="top" size="1" id="rank">


<option value="20">Top 20</option>
  <option value="50">Top 50</option>
  <option value="100">Top 100</option>
  <option value="500">Top 500</option>
  <option value="1000">Top 1000</option>
</select>
</p>
<fieldset>
<legend>Name rankings may include:</legend>
<input type="radio" name="number" value="p" id="percent">
<label for="percent">Percent of total births</label><br>
<input type="radio" name="number" value="n" id="number">
<label for="number">Number of births</label>
</fieldset>
<hr>
<input class="uef-btn uef-btn-primary" type="submit" value="  Go  ">
</form>

我正在使用 HTTPURLConnection 进行提交这是我的代码和我的测试类

public class FormSubmitServiceTest {

@Test
public void testSubmit() throws Exception {
    String url = "http://www.socialsecurity.gov/OACT/babynames/#ht=1";
    Map<String, String> data = new HashMap<String, String>();
    data.put("year", "2010");
    data.put("top", "50");
    data.put("number", "n");

    FormSubmitService service = new FormSubmitService();
    service.doSubmit(url, data);
}
}  

我的服务类完成工作

public class FormSubmitService {

    public void doSubmit(String url, Map<String, String> data) throws IOException {
        URL siteUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", 
               "application/x-www-form-urlencoded");
        conn.setUseCaches (true);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());

        Set keys = data.keySet();
        Iterator keyIter = keys.iterator();
        String content = "";
        for(int i=0; keyIter.hasNext(); i++) {
            Object key = keyIter.next();
            if(i!=0) {
                content += "&";
            }
            content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
        }
        System.out.println(content);
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = "";
        while((line=in.readLine())!=null) {
            System.out.println(line);
        }
        in.close();
    }
}

谁能告诉我为什么这在提交表单时不起作用。是不是因为我没有点击值为 GO 的提交按钮。如果是这种情况,那么我该如何实际点击它,因为我希望发送一个名称值对,但提交按钮没有名称只有一个值。

当我通过此代码发布表单时,我希望响应包含与我手动提交表单时相同的数据,即此页面上的数据 http://www.socialsecurity.gov/cgi-bin/popularnames.cgi .

但是在运行测试类时,我得到的响应中的数据与原始页面相同http://www.socialsecurity.gov/OACT/babynames/#ht=1 .

感谢所有帮助

谢谢

最佳答案

我想您会注意到,如果您将测试用例中的 URL 更改为 http://www.socialsecurity.gov/cgi-bin/popularnames.cgi一切都会好起来的。

关于java - 使用 HTTPURLConnection 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15805771/

相关文章:

Java 8 消费者和副作用

java - Java中String[](带方括号)和String(不带方括号)的区别

java.io.IOException : No authentication challenges found

Java Android 如何在Exception 中获取HTTPUrlConnection (POST) 响应代码和消息?

java - Android App : Log-in to website, 维护 session - Java

java - 如何判断cgywin使用哪个java版本?

java - HttpClient 发布以从 keycloak 获取 Bearer token

android - HttpURLConnection.getResponseCode() 卡住执行/不超时

java - 如何找到 HttpURLConnection 尝试将我重定向到的位置?

spring-mvc - 如何绕过 Openshift 上 URLConnection 的 SSL 检查