How to post parameters to a URL connected using HttpURLConnection
843841Jul 23 2004 — edited Mar 9 2006hi,
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