You can use Android's HttpURLConnection
class for that. Following is the method to make that request with parameters.
// Create Post Request
public String makePostRequest(String requestURL, String params) {
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "*/*");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(params);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Show response on activity
return text;
}
The parameters passed to this method should be encoded in order to avoid any inconvenience due to special characters. Following is the method to encode parameters
public String encodeParams(HashMap<String, String> params) throws UnsupportedEncodingException {
String encodedParams = "";
/* Display content using Iterator*/
Set set = params.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
if (encodedParams != null && !encodedParams.equals("")))
encodedParams += "&";
Map.Entry mentry = (Map.Entry) iterator.next();
encodedParams += URLEncoder.encode(mentry.getKey().toString(), "UTF-8")
+ "=" + URLEncoder.encode(mentry.getValue().toString(), "UTF-8");
}
return encodedParams;
}
In order to make Http Request, call these methods as follows:
try {
// prepare parameters for http call
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("serial", android.os.Build.SERIAL);
hashMap.put("board", android.os.Build.BOARD);
// encode parameters
String encodedParams = encodeParams(hashMap);
// create request url
String requestUrl = "http://xxxxxxxxxxxx/"; // your URL
// make a post request to server with request url create above
String response = makePostRequest(requestUrl, encodedParams, null);
return response;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
P.S. you should try running this code using background thread or AsyncTask
for better performance avoiding NetworkOnMainThread
exception.