java - 无法解决 Android 中的 POST 请求
问题描述
我知道人们已经多次问过这个问题。但它仍然给我带来了困难。
从几个地方收集代码后:比如教程,我可以写这个。
我做了什么:我检查了 GET 请求中代码的工作情况。它正在工作。
private class Myworker extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("myurl");
org.json.JSONObject df = new org.json.JSONObject();
df.put("amount", "50");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
try {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(df));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
System.out.println("n " + new String(stringBuilder));
}
} finally {
conn.disconnect();
}
} catch (Exception e) {
System.out.println("Unable *******");
e.printStackTrace();
}
return null;
}
}
public String getPostDataString(org.json.JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator itr = params.keys();
while (itr.hasNext()) {
String key = (String) itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
错误:
int responseCode=conn.getResponseCode()
也作为 415 返回。
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
请帮忙
解决方案
415 是不支持的媒体类型,这可能是由于您没有正确设置 Content-Type 标头。
尝试添加
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
将来您可能想尝试使用 http 客户端库,例如 apache httpcomponents 或 google-http-client,因为它们更易于使用。