为HttpURLConnection添加参数的最佳投票是this post
但答案是解释如何添加具有类似形式的参数 - > “用户名= usernameValue密码= passwordValue?” < -
请记住参数可以具有类似JSON对象的形式,如果您不了解POST的JSON参数,链接的答案可能会让您迷失方向。
然后这是我能提供的最佳答案。
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
JSONObject urlParameter = new JSONObject();
urlParameter.put("username", usernameValue);
urlParameter.put("password", passwordValue);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(urlParameter.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
StringBuilder sb;
sb = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} else {
System.out.println(conn.getResponseMessage());
}
String result = sb.toString();
如果您有更好的解决方案,请赐教。 TY