」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在Android中發送帖子數據:ASYNCTASK與現代方法?

如何在Android中發送帖子數據:ASYNCTASK與現代方法?

發佈於2025-03-23
瀏覽:914

How to Send POST Data in Android: AsyncTask vs. Modern Methods?
如何在為Android開發時如何在Android

Deprecated AsyncTask Method

The following code snippet demonstrates how to send POST data using the AsyncTask class:

public class CallAPI extends AsyncTask { public callapi(){ //設置上下文變量(如果需要) } @Override 受保護的void onpreexecute(){ super.onpreexecute(); } @Override 受保護的字符串doinbackground(字符串... params){ 字符串urlstring = params [0]; // url呼叫 字符串數據= params [1]; //發布數據 outputStream out = null; 嘗試 { URL URL =新URL(urlstring); httpurlconnection urlConnection =(httpurlConnection)url.openconnection(); out = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter Writer = new BufferedWriter(new UppoteStreamWriter(OUT,“ UTF-8”)); writer.write(數據); writer.flush(); writer.close(); out.close(); urlConnection.connect(); } catch(異常E){ system.out.println(e.getMessage()); } } } [2 httpclient httpclient = new defaulthtpclient(); httppost httppost = new httppost(“ http://www.yoursite.com/script.php”); 嘗試 { 列表 nameValuepairs = new ArrayList (2); nameValuepairs.Add(new BasicNameValuePair(“ ID”,“ 12345”)); nameValuepairs.Add(new BasicNameValuePair(“ StringData”,“ Hi”)); httppost.setentity(新的urlencodedformentity(nameValuepairs)); httpresponse響應= httpclient.execute(httppost); } catch(client prototocolexception e){ // TODO自動生成的捕獲塊 } catch(ioexception e){ // TODO自動生成的捕獲塊 } }

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3