Exisitng代码: 发送id并传入正文中的url和xml数据
String url = http://localhost:8080/FirstServlet/MyFirstServletMapping&id=123&pass=sDff
HttpURLConnection urlc = (HttpURLConnection) new URL(url).openConnection();
urlc.setDoOutput(true);
urlc.setRequestMethod("POST");
OutputStream out = urlc.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write("<xml>");
writer.flush();
writer.close();
现在我需要更改代码以发送id并在POST中传递。 如何更改代码以添加id并传入POST并且不会破坏服务器读取。
我尝试如下,但看到xml在传递结束时被追加。 这会在服务器端引起任何问题吗?或者这看起来不错?..有什么建议吗?
新守则:
String url = "http://localhost:8080/FirstServlet/MyFirstServletMapping";
HttpURLConnection urlc = (HttpURLConnection) new URL(url).openConnection();
urlc.setDoOutput(true);
urlc.setRequestMethod("POST");
OutputStream out = urlc.getOutputStream();
byte[] postData = setRequestData(111124l, "password5");
out.write(postData);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write("xml");
writer.flush();
writer.close();
private static byte[] setRequestData(Long prsId, String password) throws IOException {
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("id", prsId);
params.put("pass", password);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0)
postData.append('&');
try {
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
System.out.println("post data is--->"+postData.toString());
return postDataBytes;
}
输出: 在post方法
DSID - &GT; 111124 密码是 - &gt; password5xml
服务于:/ FirstServlet:结束