将 POST 中的 JsonObject 从 android 发送到服务器
Send JsonObject in POST from android to server
我想发送这个jsonobject finalObject
到这个服务器地址http://www.xxxx.com/app/pruebaurl我正在使用这个代码
try {
URL url = new URL("http://www.xxxx.com/app/pruebaurl");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(finalObject.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}catch (Exception e) {
e.printStackTrace();
}
但是当我通过调试 运行 代码时,我注意到从行
跳转时
httpURLConnection.connect();
到行
OutputStream outputStream = httpURLConnection.getOutputStream();
生成错误并转到异常,它告诉我以下内容
android.os.NetworkOnMainThreadException
我正在处理一个片段,我可以做些什么来修复这个错误。
在 android 中,您不能在主线程(UI 线程)上进行网络操作。
请使用其他线程,如:How to fix android.os.NetworkOnMainThreadException?
使用 AsyncTask 或任何线程来解决这个问题。
您需要使用 AsyncTask 来执行网络操作。您不能在主线程上执行它。
我想发送这个jsonobject finalObject
到这个服务器地址http://www.xxxx.com/app/pruebaurl我正在使用这个代码
try {
URL url = new URL("http://www.xxxx.com/app/pruebaurl");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(finalObject.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}catch (Exception e) {
e.printStackTrace();
}
但是当我通过调试 运行 代码时,我注意到从行
跳转时 httpURLConnection.connect();
到行
OutputStream outputStream = httpURLConnection.getOutputStream();
生成错误并转到异常,它告诉我以下内容
android.os.NetworkOnMainThreadException
我正在处理一个片段,我可以做些什么来修复这个错误。
在 android 中,您不能在主线程(UI 线程)上进行网络操作。 请使用其他线程,如:How to fix android.os.NetworkOnMainThreadException?
使用 AsyncTask 或任何线程来解决这个问题。
您需要使用 AsyncTask 来执行网络操作。您不能在主线程上执行它。