3 回答

TA貢獻1848條經驗 獲得超6個贊
new AsyncTask<Void,Void,Void>(){
private Exception exception;
@Override
protected Void doInBackground(Void... voids) {
try{
URL url= new URL("http://yourserveraddress/resource.extension");
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//write additional POST data to url.getOutputStream() if you wanna use POST method
}catch (Exception ex){
this.exception=ex;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();

TA貢獻1848條經驗 獲得超10個贊
有很多方法可以從應用程序發送 HTTP 請求。例如使用HttpURLConnectionwithGET方法,您可以按如下方式進行:
StringBuilder content = new StringBuilder();
try {
URL u1 = new URL(url);
HttpURLConnection uc1 = (HttpURLConnection) u1.openConnection();
if (uc1.getResponseCode()==HttpURLConnection.HTTP_OK) {
InputStream is = uc1.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = br.readLine()) != null) {
content.append(line).append("\n");
}
}//other codes

TA貢獻1847條經驗 獲得超11個贊
您應該創建 HTTP 連接和 HTTP 請求。
您可以通過以下幾種方式做到這一點:
HttpURLConnection
在 Java 中使用本機可用 - 有關詳細信息,請參閱本教程:https : //www.mkyong.com/java/how-to-send-http-request-getpost-in-java/使用專用庫,它以稍微好一點的方式做同樣的事情 - 例如OkHttp
請記住,發送 HTTP 請求是非確定性操作,您應該在單獨的非 UI 線程中執行它以保持 UI 暢通。您可以通過AsyncTask 來完成,這是最簡單的解決方案,但您也可以將RxJava與RxAndroid或其他方法一起使用。
添加回答
舉報