我最近學習了 Java,我正在嘗試在 Android Studio 中制作一個可以訪問 API 的簡單應用程式。我正在嘗試使用 HttpURLConnection 但我遇到了類問題,當我嘗試組合這兩個類時出現錯誤,并且似乎無法在沒有兩者的情況下使其作業。
我的目標是使我的名為 TextView1 的 TextView 能夠更改以顯示來自以下內容的代碼。
http.getResponseCode() " " http.getResponseMessage()
代碼
package com.example.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.net.*;
public class MainActivity extends AppCompatActivity {
public void main(String[] args) throws Exception {
// Sending get request
setContentView(R.layout.activity_main);
URL url = new URL("https://reqbin.com/echo/get/json");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestProperty("Content-Type", "application/json");
http.setRequestProperty("Accept", "application/json");
String responsecode = http.getResponseCode() " " http.getResponseMessage();
http.disconnect();
}
public void onCreate(Bundle savedInstanceState) {
// Sending get request
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.TextView1);
String string = "Hello";
textView.setText(string);
}
}
uj5u.com熱心網友回復:
首先,據我所知,Android 上沒有使用“main”方法。
對于 API 呼叫,您可能有更好的選擇:
- 使用框架(如最常用的改造)
- 使用 Thread 并通過 runOnUIThread 方法更新您的 UI
- 使用 AsyncTask(已棄用)
- 或者其他方式
我的觀點是你顯然不能在 UI 執行緒上運行 API 呼叫:試圖為你加載 Activity 的執行緒。據我記得,Android 通過顯式例外來防止這種情況發生。
所以,你可以做的是呼叫一個新的執行緒,例如在你的 onCreate 方法上,你在那里呼叫 HttpCall,你得到回應(例如在字串上)然后通過 runOnUIThread() 方法更新你的 textView。進入runOnUIThread,如果你做了這樣的事情,你可以直接呼叫你的textView:
TextView textView;
public void onCreate(Bundle savedInstanceState) {
// Sending get request
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.TextView1);
new Thread(); // you create your thread here
}
然后在 runOnUIthread 上,您可以執行以下操作:
String responsecode = http.getResponseCode() " " http.getResponseMessage();
textView.setText(responsecode);
uj5u.com熱心網友回復:
可能是您的代碼不起作用,因為您沒有閱讀流。
在閱讀回應之前嘗試此行:
InputStream is=URLConnection.getInputStream();
while(is.read>=0);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447977.html
