这只是Q& A。仅仅意味着一个维基百科。我经常搜索以实现这一目标。所有人都发布了不同类型的答案。我现在成功使用此代码。所以我想与所有人分享。
您的HttpURLConnection
必须位于异步任务(doInBackground)内。
步骤:
param=val¶m2=val2
HttpUrlConnection
OutputStream
用于附加值。InputStream
设置参数:
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());
}