Sending an HTTP POST request with parameters

suggest change

Use a HashMap to store the parameters that should be sent to the server through POST parameters:

HashMap<String, String> params = new HashMap<String, String>();

Once the params HashMap is populated, create the StringBuilder that will be used to send them to the server:

StringBuilder sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
    try {
        if (i != 0){
            sbParams.append("&");
        }
        sbParams.append(key).append("=")
                .append(URLEncoder.encode(params.get(key), "UTF-8"));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    i++;
}

Then, create the HttpURLConnection, open the connection, and send the POST parameters:

try{
    String url = "http://www.example.com/test.php";
    URL urlObj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    
    conn.connect();
    
    String paramsString = sbParams.toString();
    
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(paramsString);
    wr.flush();
    wr.close();
} catch (IOException e) {
  e.printStackTrace();
}

Then receive the result that the server sends back. conn is declared inside the previous try, so this block does not see it. DataOutputStream.writeBytes writes the low eight bits of each character, not UTF-8, and the parameter names are not encoded. The connection is opened from this code, so it does not belong on the main thread.

try {
  InputStream in = new BufferedInputStream(conn.getInputStream());
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  StringBuilder result = new StringBuilder();
  String line;
  while ((line = reader.readLine()) != null) {
    result.append(line);
  }

  Log.d("test", "result from server: " + result.toString());

} catch (IOException e) {
  e.printStackTrace();
} finally {
    if (conn != null) {
        conn.disconnect();
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents