【发布时间】:2019-10-28 04:34:45
【问题描述】:
我想使用 HTTP (POST) 从 Android 向服务器发送 JSON。
但停在下面一行:
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
我为 HTTP 使用了一个线程,并添加了以下清单:
<uses-permission android:name="android.permission.INTERNET" />
但结果并没有改变。
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private String PostUrl = "http://localhost:3000";
private String JSON = "{\"test\":\"100\"}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callPost();
}
public void callPost() {
handler.post(new Runnable() {
@Override
public void run() {
HttpURLConnection con = null;
try{
URL url = new URL(PostUrl);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/JSON; charset=utf-8");
Log.d("debug", "----- All right here -----");
OutputStreamWriter out = new
OutputStreamWriter(con.getOutputStream());
Log.d("debug", "----- This message is not displayed -----");
out.write(JSON);
out.flush();
con.connect();
} catch (Exception e){
}
}
});
}
}
没有错误,只显示“----- All right here -----”。
【问题讨论】:
-
localhost:3000指向当前设备,除非明确更改为指向远程主机。并查看堆栈跟踪使用e.printStackTrace(); -
感谢您的快速回复。我将“localhost:3000”更改为服务器的IP地址,但这种情况并没有改变。当我尝试 e.printStackTrace(); , 显示“android.os.NetworkOnMainThreadException”。
-
This 可以帮你解决