user2699073
user2699073

Reputation: 71

How to make an HTTP POST URL connection?

I am accessing a web service by an HTTP POST method as below:

But the response contains nothing. I was expecting a JSON string here. Are JSON read in a different way?

Upvotes: 2

Views: 396

Answers (4)

Shamim Ahmmed
Shamim Ahmmed

Reputation: 8383

You can keep the type as HttpURLConnection instead of URLConnection. It allows to specify HTTP method.

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 122026

Adding to Shammiz answer

Without cast Make use of URLConnection.html#setDoOutput(boolean)

A URL connection can be used for input and/or output. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

Passing true, triggers post.

Upvotes: 0

sr01853
sr01853

Reputation: 6121

The problem is here

URLConnection connection = (HttpURLConnection)url.openConnection();

make connection an instance of HttpURLConnection

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44854

I agree that using a HttpUtlConnection or HTTPClient is going to make you life easier, but have a look at setDoOutput

http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#setDoOutput(boolean)

and

What exactly does URLConnection.setDoOutput() affect?

Upvotes: 0

Related Questions