使用Java自动提交HTML表单以查找杂货店时间

时间:2011-07-11 08:23:38

标签: java html forms form-submit

我正在尝试使用Java自动化表单提交以获取杂货店的时间:

www.giantfood.com

我已经发布了查询以及表单的隐藏里程和storeType字段,但我的output.html只是原始的网页页眉和页脚,正文中有错误消息。我做错了什么?

import java.io.*;
import java.net.*;

public class PostHTML
{
  public static void main(String[] args)
  {
    try
    {
      URL url = new URL( "http://www.giantfood.com/our_stores/locator/store_search.htm" );

      HttpURLConnection hConnection = (HttpURLConnection)
                             url.openConnection();
      HttpURLConnection.setFollowRedirects( true );

      hConnection.setDoOutput( true );
      hConnection.setRequestMethod("POST"); 

      PrintStream ps = new PrintStream( hConnection.getOutputStream() );
      ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY");
      ps.close();

      hConnection.connect();

      if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
      {
        InputStream is = hConnection.getInputStream();
        OutputStream os = new FileOutputStream("output.html");
        int data;
        while((data=is.read()) != -1)
        {
          os.write(data);
        }
        is.close();
        os.close();
        hConnection.disconnect();
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }
}

更新

谢谢!使用&的工作。我正在尝试使用HttpClient但我现在又收到了另一个错误:

package clientwithresponsehandler;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class ClientWithResponseHandler {

    public static void main(String[] args) throws Exception {

        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpost = new HttpPost("http://www.giantfood.com/our_stores/locator/store_search.htm");

            System.out.println("executing request " + httpost.getURI());

            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("groceryStoreAddress", "20878"));
            nvps.add(new BasicNameValuePair("groceryStoreMiles", "10"));
            nvps.add(new BasicNameValuePair("storeType", "GROCERY"));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httpost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            System.out.println("----------------------------------------");
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}

输出:

运行: 执行请求http://www.giantfood.com/our_stores/locator/store_search.htm 线程“main”中的异常org.apache.http.client.HttpResponseException:暂时移动     at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:67)     at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:55)     在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:945)     在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:919)     在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:910)     at clientwithresponsehandler.ClientWithResponseHandler.main(ClientWithResponseHandler.java:39) Java结果:1 建立成功(总时间:1秒)

我不明白Moved Temporarily错误。

2 个答案:

答案 0 :(得分:2)

尝试使用

ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY")

代替

顺便说一下,使用某些http库比较容易,比如Apache HttpClient

答案 1 :(得分:0)

通过了解HTML重定向来解决暂时移动:

Httpclient 4, error 302. How to redirect?