java中POST请求的问题

时间:2011-06-21 21:53:17

标签: java post

我尝试用Java编程发送POST请求并获得以下异常:

  

“org.apache.http.client.HttpResponseException:Forbidden”

但是,如果我使用此表单在浏览器中发送请求:

<form method=post action="http://gametest.phpnet.us">
    <p>Type : <input type=text name=request_type>
    <p>Name : <input type=text name=user_name>
    <p>Password : <input type=text name=user_password>
    <p><input type=submit name=send value=Send>
</form>

一切正常(尝试使用任何名称和密码,类型必须为“注册”,服务器必须返回xml“<code>0</code>”)。

这是java代码的示例:

HttpParams defHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(defHttpParams, 5000);   
HttpConnectionParams.setSoTimeout(defHttpParams, 5000); 
String mServerUrl = "http://gametest.phpnet.us/index.php";
DefaultHttpClient mClient = new DefaultHttpClient(defHttpParams);
HttpPost postMethod = new HttpPost(mServerUrl);

postMethod.setEntity(new UrlEncodedFormEntity( [...some nameValuePairs] ));

try {
    ResponseHandler<String> httpResponceHandler = new BasicResponseHandler();
    responce = mClient.execute(postMethod, httpResponceHandler);
}
catch (Throwable t) {
    //...
}

(如果我使用本地apache服务器,那么一切正常,但在phpnet.us上我得到例外。)

如何使Java代码正常工作?

1 个答案:

答案 0 :(得分:6)

尝试使用htmlunit

  // Create client with settings
  final WebClient webClient = new WebClient();
  webClient.setTimeout(5000);

  // Create web request
  WebRequest requestSettings = new WebRequest(new URL("http://www.amazon.com/s/ref=nb_sb_noss"), HttpMethod.POST);

  // Set the request parameters
  requestSettings.setRequestParameters(new ArrayList());
  requestSettings.getRequestParameters().add(new NameValuePair("field-keywords", "Doctor Who"));

  Page page = webClient.getPage(requestSettings);
  page.getWebResponse().getStatusCode();