0

I'm trying to post data to url with parameters. And I need to post some data string along with parameters.

HttpURLConnection cnn = null;
InputStream strIn = null;
String ret = null;
try {
  URL url = new URL("http://server.com?param1=1&param2=2");
  cnn = getConnection(url);
  cnn.setConnectTimeout(_nTimeout);
  cnn.setReadTimeout(_nTimeout);
  cnn.setDoOutput(true);
  cnn.setRequestMethod("POST");
  cnn.setUseCaches(false);
  cnn.setRequestProperty("Content-Type", "text/plain");
  cnn.connect();
  DataOutputStream strOut = new DataOutputStream(cnn.getOutputStream ());
  strOut.write(myData.getBytes("UTF-8"));
  strOut.flush();
  strOut.close();
  int status = cnn.getResponseCode();
  if (status == 200){
    strIn = cnn.getInputStream();
  }
  else {
    strIn = cnn.getErrorStream();
  }
  BufferedReader rd = new BufferedReader(new InputStreamReader(strIn));
  StringBuilder response = new StringBuilder();
  String line;
  while((line = rd.readLine()) != null) {
    response.append(line);
    response.append('\r');
  }
  ret = response.toString();
} catch (IOException e) {
  e.printStackTrace();
  throw e;
} 
catch (Exception e) {
  e.printStackTrace();
  IOException exNew = new IOException("HTTP unknown exception", e.getCause());
  throw exNew;
} finally {
  if (strIn != null) {
    Utility.close(strIn);
  }
  if (cnn != null) {
    cnn.disconnect();
  }
}
return ret;

Seems, my parameters are ignored. I've got to know the parameters should be inserted into body of post message:

StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
  if (postData.length() != 0) postData.append('&');
  postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
  postData.append('=');
  postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
cnn.getOutputStream().write(postDataBytes);

Then where my data myData should be placed to?

Belowee P.
  • 134
  • 12
  • Possible duplicate of [How to add parameters to HttpURLConnection using POST](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) –  Apr 01 '16 at 13:11
  • Seems, there is no any solution. Method post cannot have parameters in URL in Android. We have to redesign API. – Belowee P. Apr 04 '16 at 06:00

0 Answers0