Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to post parameters to a URL connected using HttpURLConnection

843841Jul 23 2004 — edited Mar 9 2006
hi,

i have a problem...i need to send few parameters using post method to a URL

from a servlet..so i opend a connection to that URL using HttpURLConnection.

and used this code..

URL url = new URL("http://localhost:8080/examples/servlet/TestServlet1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setUseCaches(false);
conn.setDoOutput(true);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{ // response is good...

conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WinNT4.0; en-US; rv:1.1) Gecko/20020826");
conn.setRequestProperty("Accept-Language", "de-at");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1, utf-8;q=0.66, *;q=0.66");
StringBuffer postparameter = new StringBuffer();
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
postparameter.append(paramName + "=" + URLEncoder.encode(request.getParameterValues(paramName)));
}
OutputStreamWriter outStream = new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream()));
outStream.write(postparameter.toString());
outStream.close();
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));
String inLine;
StringBuffer result = new StringBuffer();
while ((inLine = in.readLine()) != null)

{
out.println();
out.println(inLine);
out.println();
}
in.close();

}

else
{
out.println("\n\n-----sorry connetion failed-----");
out.println("\n\nHTTP Response: " + conn.getResponseCode());
}

which i took it from some form...

but i am getting the error 405..which is - Method not allowed
i am unable to trace the error can any body please help

heral raj
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 6 2006
Added on Jul 23 2004
5 comments
834 views