2011-06-21 140 views
1

我試圖用Java編程方式發送POST請求,並得到以下異常:問題在Java POST請求

「org.apache.http.client.HttpResponseException:禁止」

但是,如果我用這種形式在瀏覽器發送請求:

<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代碼工作?

+2

PHP ???????? ... – dynamic

+0

@職場英語對話 - 誒? :) – Yorick

+0

我沒有看到任何PHP代碼。你做?或者你只是在一個很大的困惑? – dynamic

回答

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(); 
+0

哇,這是有效的。但正如我所看到的,htmlunit使用與上述代碼相同的庫。我需要清理。 – Yorick

+0

沒錯,htmlunit確實使用了上面使用的apache httpcomponents。我發現使用htmlunit更容易,它也支持javascript。 – telm

+0

區別在於:「postMethod.setHeader(」User-Agent「,」Mozilla/4.0(compatible; MSIE 7.0; Windows NT 5.1)「);」所以我其實不需要htmlunit。無論如何,謝謝你的建議。 – Yorick