我需要向URL發送POST請求併發送一些請求參數。我爲此使用HttpURLConnectionAPI。但我的問題是我沒有得到servlet中的任何請求參數。雖然我看到參數存在於請求主體中,但是當我使用request.getReader打印請求主體時。以下是客戶端代碼。任何機構可以指定這是否是在POST請求中發送請求參數的正確方法?如何使用HttpUrlConnection發送POST請求中的requestparameter
String urlstr = "http://serverAddress/webappname/TestServlet";
String params = "¶mname=paramvalue";
URL url = new URL(urlstr);
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("Content-Type", "text/xml");
urlconn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));
urlconn.setRequestProperty("Content-Language", "en-US");
OutputStream os = urlconn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.close();
os.close();
不知道你是否需要領先&在你的params字符串。另外,你應該writer.write(params.getBytes()) – Kal 2011-05-02 16:40:51