[英]How can I make a simple HTTP request in MainActivity.java? (Android Studio)
我正在使用 Android Studio,我花了幾個小時試圖在我的 MainActivity.java 文件中執行一個簡單的 HTTP 請求,並嘗試了多種方法,並看到了許多關於該主題的網頁,但無法弄清楚。
當我嘗試 OkHttp 時,我收到關於無法在主線程上執行此操作的錯誤。 現在我正在嘗試這樣做:
public static String getUrlContent(String sUrl) throws Exception {
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}
我將該方法直接放在 MainActivity.java 中,我的單擊事件從另一個也在 MainActivity.java 中的方法中執行它:
try {
String str = getUrlContent("https://example.com/WAN_IP.php");
displayMessage(str);
}
catch(Exception e){
displayMessage(e.getMessage());
}
但是現在沒有崩潰,我可以看出在以“BufferedReader”開頭的行上拋出了一個異常,但 e.getMessage() 是空白的。
我是 Android Studio 和 java 的新手,所以請善待並幫助我解決這個非常基本的問題。 最終我需要向服務器發送請求,似乎 OkHttp 是最好的方法,但我沒有找到在線任何地方記錄的 Android Studio 中 OkHttp 的“Hello World”。
您不應在主線程上發出網絡請求。 延遲是不可預測的,它可能會凍結 UI。
如果您使用主線程中的HttpUrlConnection
對象,Android 會通過拋出異常來強制執行此行為。
然后,您應該在后台發出網絡請求,然后在主線程上更新 UI。 AsyncTask
類對於這個用例非常方便!
private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}
你以這種方式開始這個過程:
new GetUrlContentTask().execute(sUrl)
如果您使用 okhttp 然后調用 aysnc 嘗試波紋管代碼
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.setConnectTimeout(15, TimeUnit.SECONDS);
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
Log.e(responseHeaders.name(i) , responseHeaders.value(i));
}
Log.e("response",response.body().string());
}
});
}
您可以使用依賴來發出 HTTP 請求或 HTTPS 請求,使用 OkHttp
訪問: https : //square.github.io/okhttp
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.