我嘗試使用 HttpURLConnection 向我的本地(xampp)服務器發送一個帶有這樣的 url 的 post 請求http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2,服務器 php 檔案在 url 中獲取引數并將資料發送到 mysql 資料庫。
該 url 在郵遞員代理上運行良好,甚至另一個 get 方法請求在 android 應用程式中運行順利。
然而,當我使用以下代碼嘗試 post 方法時:
public void postOrder() {
TextView tv = findViewById(R.id.tv1);
Thread t = new Thread( new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(10000 /*ms*/);
conn.setConnectTimeout(15000 /*ms*/);
conn.connect();
}
catch (IOException e) {
Log.d("HTTP error: ", e.toString());
}
finally {
conn.disconnect();
}
}
} );
t.start();
}
它從未發送過 url,因此沒有資料存盤到資料庫中。
經過 6 小時的反復試驗、谷歌和搜索,我添加了這行代碼:
InputStream is = conn.getInputStream();
它終于奏效了。請回答我為什么它只在添加這行代碼后才有效,它有什么作用?我以為網址是在之后觸發的conn.connect();
uj5u.com熱心網友回復:
呼叫connect()僅連接,但尚未發送任何內容。呼叫getResponseCode()以強制發送請求。getInputStream()如果回應不是 2xx (在這種情況下,您需要getErrorStream()) ,該方法比拋出例外的方法更安全。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425895.html
標籤:爪哇 安卓 网址 http-post httpurl连接
上一篇:無法在Python中卷曲POST
