问题
It's Just Q&A. means just a Wiki Post. I searched a lot to make this happen. All are posting different kind of answers. I am successfully using this code now. So I'd like to share to all.
Your HttpURLConnection
must be inside Async Task (doInBackground).
Steps:
- Setting up parameters in Map Function
- Building string in form:
param=val¶m2=val2
- Setting up
HttpUrlConnection
OutputStream
is used to attach values.- Reading response from server using
InputStream
Set Parameters:
Map<String,Object> params = new LinkedHashMap<>();
params.put("tag", "sda");
try {
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"));
}
String postdata = postData.toString();
Log.w("postData", postdata); //HERE Postdata will be 'param=val'
byte[] postDataBytes = postData.toString().getBytes();
//NOW, Establishes HttpConnection
URL url = new URL(config.URL_REGISTER);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
//Read the Response from Server. I use echo json_encode($response); in php file. where $response["key"] = $value;
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("connec()", "UnsupportedEncodingException: " + e.toString());
} catch (ProtocolException e) {
e.printStackTrace();
Log.e("connec()", "ProtocolException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("connec()", "IOException: " + e.toString());
}
来源:https://stackoverflow.com/questions/33448973/android-httpurlconnection-parameters-from-mapstring-object-via-post-method