0

Exisitng code : Sending id and pass in url and xml data in body

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();

Now I need to change the code to send id and pass also in POST. How can i change the code to add id and pass in POST and do not break the server read.

I tried as below but am seeing xml is getting appended at end of pass. Will this cause any issue at server side? Or this looks fine?..Any suggestions please?

New Code:

    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;    
}

Output: in post method

dsid-->111124 password is-->password5xml

Served at: /FirstServlet: end

  • 3
    Possible duplicate of [How to add parameters to HttpURLConnection using POST](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) – AxelH Feb 09 '17 at 08:49
  • seems that you write the postData also as the POST body not the url parameter. – Troy Young Feb 09 '17 at 08:56
  • edited the question to be more clear..Please comment – user7539027 Feb 09 '17 at 20:46

0 Answers0