[英]Java , android app. Can not send post request HttpURLConnection conn
我正在嘗試通過以下步驟發送包含掃描設備的 mac 地址的 post 請求:1/ 掃描設備 2/ 將設備 mac 地址發送到服務器 3/ 以“1”和“-1”返回響應
-----如果 1 -> 設備正確
-----if -1 -> 設備不正確
通過列出設備可以,但是發送 post 請求不起作用,捕獲服務器,沒有發出請求
private void scanLeDevice(final boolean enable) {
final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
uhf.stopScanBTDevices();
cancelButton.setText(R.string.scan);
}
}, SCAN_PERIOD);
mScanning = true;
uhf.startScanBTDevices(new ScanBTCallback() {
@Override
public void getDevices(final BluetoothDevice bluetoothDevice, final int rssi, byte[] bytes) {
runOnUiThread(new Runnable() {
@Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
String correct_device = "";
String device_mac = bluetoothDevice.getAddress();
String device_name = bluetoothDevice.getName();
// response correct_device = 1 == correct device, will available in list
// response correct_device = -1 == incorrect, does not need to appear in list
try {
url = new URL("http://10.10.10.212/api/is_correct_device/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes("{ \"check_update\" : " + device_mac + " }");
os.flush();
os.close();
correct_device = conn.getResponseMessage();
} catch (Exception e) {
e.printStackTrace();
}
if (correct_device.equals("1")) {
MyDevice myDevice = new MyDevice(device_mac, device_name);
addDevice(myDevice, rssi);
}
conn.disconnect();
}
});
}
});
cancelButton.setText(R.string.cancel);
} else {
mScanning = false;
uhf.stopScanBTDevices();
cancelButton.setText(R.string.scan);
}
}
謝謝你救我!
您正在從runOnUiThread
調用url.openConnection()
。
這是不可能的!
Android 中的所有網絡通信代碼都必須在后台線程中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.