Yury
Yury

Reputation: 93

Problems with POST request in java

I try to send a POST request programmatically in Java and get the following exception:

"org.apache.http.client.HttpResponseException: Forbidden"

However, if I use this form to send request in browser:

<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>

everything works fine (try with any Name and Password, Type must be "register", server must return xml "<code>0</code>").

Here is example of java code:

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) {
    //...
}

(If I use local apache server, then everything works fine, but on phpnet.us I get exception.)

What should I do to make Java code work?

Upvotes: 1

Views: 4787

Answers (1)

telm
telm

Reputation: 472

Try using 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();

Upvotes: 6

Related Questions