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;

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:

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:


HttpURLConnection:
* Sending an HTTP POST request with parameters

Table Of Contents
2 Gradle
5 Intent
17 Service
19 WebView
30 HttpURLConnection
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
90 Spinner
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
261 Fastjson
263 Jackson
267 Smartcard