HTTP POST Requests in Java

458 views Asked by At

Basically what I'm trying to do is connect to the Pastebin API with a PHP page I created. It seems as if the parameters are not inputting. Here's my code:

String urlParameters = "?api_dev_key=" + main.getKey() + "&api_user_name=" + username + "&api_user_password=" + password; URL url = new URL("http://pastebinclient.tk/server/login.php" + urlParameters);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36");

connection.setUseCaches(false);
connection.setDoOutput(true);

I used http://hurl.it with the same parameters and it worked fine. On my page, it is setup so that if the parameters aren't all inputted then it returns a message saying so, and that's what has been happening. Sorry that I'm asking a question that's already been answered, but the answers haven't helped.

2

There are 2 answers

1
Deadron On

You are not actually submitting parameters in the body of your POST request. You are submitting them as query parameters in the code. Depending on how the webservice is written it may or may not accept params sent as query params. It looks like in this case it does not. Refer to Java - sending HTTP parameters via POST method easily for an example of how to submit your params as a part of the POST body.

0
Beno On

I recomend http-request built on apache http api.

private static final HttpRequest<?> HTTP_REQUEST = 
      HttpRequestBuilder.createPost("http://pastebinclient.tk/server/login.php")
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .addDefaultHeader("Content-Type", "application/x-www-form-urlencoded") // I think there is no need
           .addDefaultHeader("Content-Language", "en-US")
           .addDefaultHeader("Accept", "*/*")
           .addDefaultHeader("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36")
           .build();

public void send(){
   ResponseHandler<?> handler = HTTP_REQUEST.executeWithQuery(urlParameters);
   int statusCode = handler.getStatucCode();
}