问题描述: 在Android 10及以上的设备上,使用XMLHttpRequest进行POST请求时,发现POST请求的数据为空。
解决方法: Android 10及以上的设备对网络请求的安全性进行了加强,不再允许使用非加密的明文HTTP请求。因此,需要修改代码,使用加密的HTTPS请求。
以下是一个修改后的示例代码:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostTask extends AsyncTask {
private static final String TAG = "HttpPostTask";
@Override
protected String doInBackground(String... params) {
String url = params[0];
String data = params[1];
try {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
JSONObject jsonData = new JSONObject();
jsonData.put("data", data);
OutputStream os = conn.getOutputStream();
os.write(jsonData.toString().getBytes("utf-8"));
os.flush();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "HTTP Error: " + responseCode;
}
} catch (Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
return "Error: " + e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
Log.d(TAG, "Response: " + result);
// 处理服务器返回的数据
}
}
使用示例:
String url = "https://example.com/api";
String data = "Hello, world!";
new HttpPostTask().execute(url, data);
需要注意的是,示例中的URL需要替换成实际的服务器地址,data可以根据实际需要进行修改。同时,需要在AndroidManifest.xml中添加网络访问权限:
通过以上修改,即可在Android 10及以上的设备上正常发送POST请求。