[英]Sending HTTPS GET request from android to python is not working
我正在嘗試在 android 應用程序(客戶端)和我的筆記本電腦(服務器)之間建立 https 連接。 我的 https 服務器作為 python 腳本運行(帶有letsencrypt 證書),只要我嘗試將它與 chrome 或其他 python 腳本連接,它就可以正常工作。
現在我想在我的 android 應用程序中實現客戶端。 因此,我向AndroidManifest.xml
添加了權限:
<uses-permission android:name="android.permission.INTERNET"/>
並將以下幾行添加到我的MainActivity.java
(基於Android Developers上的HttpURLConnection 參考!:
public void onButtonClicked(String message) {
try {
URL url = new URL("https://foo.bar.com/");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
mSecondFragment.updateMessage(message);
}
目前我只想建立到我的 https 服務器的連接並發送一個簡單的 GET 請求而不接收任何數據。 但我的目標是解析一個額外的鍵值對以及將由服務器處理的GET
請求:
"https://foo.bar.com?a=1"
我試圖讓它盡可能簡單(這就是我想使用java.net.HttpURLConnection
的原因),但我認為問題並不像我預期的那么簡單。
也許有人遇到了同樣的問題,可以幫助我解決這個問題:)
編輯(感謝@atomicrat2552 和@petey):
我添加了一個額外的類,將請求作為 AsyncTask 處理:
public class NetworkConnection extends AsyncTask<String, Void, NetworkConnection.Result> {
static class Result {
public String mResultValue;
public Exception mException;
public Result(String resultValue) {
mResultValue = resultValue;
}
public Result(Exception exception){
mException = exception;
}
}
protected NetworkConnection.Result doInBackground(String... urls) {
Result result = null;
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.connect();
result = new Result("Done");
}catch(Exception e) {
result = new Result(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result;
}
}
這導致MainActivity.java
一個簡化的 onButtonClick 方法:
NetworkConnection nwConn = new NetworkConnection();
public void onButtonClicked(String message) {
nwConn.execute("https://foo.bar.com");
mSecondFragment.updateMessage(message);
}
我再次嘗試簡化代碼,以便獲得一個可以在以后擴展的小型工作代碼。 該應用程序不再崩潰,但我的服務器仍然沒有顯示任何請求。 如果我在手機上使用瀏覽器,一切正常。 任何的想法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.