This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Sockets and Internet Protocols and the fly likes Servlet post to server using HttpUrlConnection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Servlet post to server using HttpUrlConnection" Watch "Servlet post to server using HttpUrlConnection" New topic
Author

Servlet post to server using HttpUrlConnection

Nicky Eng
Ranch Hand

Joined: Mar 26, 2005
Posts: 378
Hi there,


In my servlet I will send data to a URL using method 'POST' with HttpUrlConnection class.

But it happens to return me http code=411 from server which indicates content-length field.

I try to send few data like "userid=username&pass=1234&msg=try+again"

Here is my part of code:


My question is

1: Does content-length field is necessary in a POST method ?
2: Even if I coded "connection.setRequestProperty("Content-length", length) " after connection.setRequestMethod("POST"), It will give me NO return_code value. Why?


Can anyone please help me..i'm stuck for few days..


thanks in advance.

Nick


From NickyEng
Diploma in Computer Studies
SCJP 1.4
SCWCD 1.4
Formula 1 app by Maxis (Playbook)
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
1. Content-length is not generally necessary but since you got a 411, the service you are calling requires it.
2. NO return value means what? did that print statement even execute?

Where did you write the body of the POST?

Bill
Nicky Eng
Ranch Hand

Joined: Mar 26, 2005
Posts: 378
William Brogden wrote:1. Content-length is not generally necessary but since you got a 411, the service you are calling requires it.
2. NO return value means what? did that print statement even execute?

Where did you write the body of the POST?

Bill




params string contents the body...


Is that the way of posting params to server using POST method?
Nicky Eng
Ranch Hand

Joined: Mar 26, 2005
Posts: 378
I've try again this morning but this time i added in content-length...but it wont retun me the response http code




The result is :

b4 calling connect()
after calling connect()


"return_code" is not printed.
I dont understand, why it cannot return me the value of response code?

anyone help ?

Nick
Rok Štelcer
Ranch Hand

Joined: Nov 03, 2009
Posts: 101
Hi,

On the first look, I would say that the API call getResponseCode() throws IOException.

Try to replace the existing call (Exception block):
- e.printStackTrace(); // standard error stream
with the following one:
- System.out.println("Exception : " + e.toString()); // standard output stream
and let us know the result.



Regards,
Rok


SCJP, SCWCD
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
I dont think that URL constructor works the way you are trying to use it.

Surely that last parameter

creates a String which is NOT a file name and a MalformedURLException is thrown.

Bill
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

I don't think so. That would cause the "b4 calling connect()" and "after calling connect()" to not be printed, as they come after the construction of the URL.

Nicky, I just want to know: is the getResponseCode() method "hanging", or is an exception thrown and printed?

And Rok, the full stack trace is always more useful for debugging than just the toString() value which is just the class and message. The stack trace also indicates exactly where the exception is thrown from.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
cmscreativeguy Kumar
Greenhorn

Joined: Oct 04, 2012
Posts: 1

Check this COde ... ITs working for me :)

URL url = null;
String result = "";
HttpURLConnection connection = null;
try{
//Create connection
url = new URL(desiredUrl);

connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","text/html");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Length", Integer.toString("your message length here ".length()));
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Protocol-Version",httpVersion);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);


if(connection.getResponseCode() == 200)
{
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonText);
wr.flush();
wr.close();

// get data
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
// Print HERE
}
rd.close();

}

} catch (Exception e)
{

e.printStackTrace();
}finally{
if(connection != null) {
connection.disconnect();
}
}




 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Servlet post to server using HttpUrlConnection
 
Similar Threads
HttpURLConnection woes!
Connecting to the webserver from simple java program with main method
Relation between Internet Explorer and Socket Connection
Servlet design - static methods
Non Blocking HttpPost Request / Client-Server communication