Android開發(fā)使用URLConnection進行網(wǎng)絡(luò)編程詳解
本文實例講述了Android開發(fā)使用URLConnection進行網(wǎng)絡(luò)編程。分享給大家供大家參考,具體如下:
URL的openConnection()
方法將返回一個URLConnection,該對象表示應(yīng)用程序和URL之間的通信連接,程序可以通過URLConnection實例向該URL發(fā)送請求,讀取URL引用的資源。通常創(chuàng)建一個和URL的連接,并發(fā)送請求,讀取此URL引用的資源。
需要如下步驟:
a)通過調(diào)用URL對象openConnection()
方法來創(chuàng)建URLConnection對象
b)設(shè)置URLConnection的參數(shù)和普通請求屬性
conn.setRequestProperty("accept","*/*"); conn.setRequestProperty("connection","Keep-Alive"); conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
發(fā)送POST請求必須設(shè)置如下兩行
conn.setDoInput(true)
:設(shè)置該URLConnection的doInput請求頭字段的值
coon.setDoOutput(true)
:
c)調(diào)用connect()
:打開到此URL引用的資源的通信鏈接(如果尚未建立這樣的連接)。
如果在已打開連接(此時 connected 字段的值為 true)的情況下調(diào)用 connect 方法,則忽略該調(diào)用.
URLConnection 對象經(jīng)歷兩個階段:首先創(chuàng)建對象,然后建立連接。
在創(chuàng)建對象之后,建立連接之前,可指定各種選項(例如doInput和UseCaches).連接后再進行設(shè)置就會發(fā)生錯誤。連接后才能進行的操作(例如getContentLength),如有必要,將隱式執(zhí)行連接.
d)如果只是發(fā)送GET方式請求,使用connect方法建立和遠程資源之間的實際連接即可,在請求的地址中傳入數(shù)據(jù)。
如果需要發(fā)送Post方法請求。需要獲取URLConnection實例對應(yīng)的輸出流來發(fā)送請求參數(shù),
PrintWriter out=new PrintWriter(conn.getOutputStream()); //解決亂碼問題 String n=EncodingUtils.getString("張三".getBytes(),"UTF-8"); out.write("name="+n+"&pwd="+pwd); out.flush();//刷新輸出流的緩沖
e)遠程資源變?yōu)榭捎?,程序可以訪問遠程資源的頭字段或通過輸入流讀取遠程資源的數(shù)據(jù)。
getInputStream()
獲取輸入流。
從輸入流讀取response的數(shù)據(jù)。
注意:
1)如果既要使用輸入流讀取URLConnection響應(yīng)的內(nèi)容,也要使用輸出流發(fā)送請求參數(shù),一定要先使用輸出流,再使用輸入流。
2)借助于URLConnection類的幫助,應(yīng)用程序可以非常方便地與指定站點交換信息,包括發(fā)送GET請求,POST請求,并獲取網(wǎng)站的響應(yīng)等。
代碼編寫步驟如下:
1.先寫一個服務(wù)器-web工程
新建一個Servlet--LoginServlet,簡單實現(xiàn)用戶的登錄~
@WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginServlet() { // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String name=request.getParameter("name"); String pwd=request.getParameter("pwd"); System.out.println(name+" "+pwd); OutputStream os=response.getOutputStream(); if("xuxu".equals(name)&&"123".equals(pwd)){ os.write(("成功").getBytes("UTF-8")); }else{ os.write(("失敗").getBytes("UTF-8")); } os.flush(); os.close(); } }
2.新建一個android項目,在MainActivity中分別使用get方法和post方法實現(xiàn)用戶的登錄
public class MainActivity extends Activity { private EditText name,pwd; public void get(View view){ new Thread(){ public void run() { try { URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"+ "?name="+name+"&pwd="+pwd); URLConnection conn=url.openConnection(); conn.connect();//真正的建立網(wǎng)絡(luò)連接 BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream())); String line=null; StringBuffer stringBuffer=new StringBuffer();//字符串,都可以存儲和操作字符串,它是變量 while ((line=reader.readLine())!=null) { stringBuffer.append(line); } System.out.println(stringBuffer.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); } public void post(View view){ new Thread(){ public void run() { try { URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet" ); URLConnection conn=url.openConnection(); //必須設(shè)置 conn.setDoInput(true); conn.setDoOutput(true); conn.connect();//真正的建立網(wǎng)絡(luò)連接 PrintWriter printWriter=new PrintWriter(conn.getOutputStream()); printWriter.write("name="+name+"&pwd="+pwd); printWriter.flush(); printWriter.close(); BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream())); String line=null; StringBuffer stringBuffer=new StringBuffer(); while ((line=reader.readLine())!=null) { stringBuffer.append(line); } System.out.println(stringBuffer.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name=(EditText) findViewById(R.id.name); pwd=(EditText) findViewById(R.id.pwd); } }
3.運行,把Tomcat打開~
效果圖如下:
附:完整實例代碼點擊此處本站下載。
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android開發(fā)入門與進階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設(shè)計有所幫助。
- Android使用URLConnection提交請求的實現(xiàn)
- Android HttpURLConnection.getResponseCode()錯誤解決方法
- Android 中HttpURLConnection與HttpClient使用的簡單實例
- Android中HttpURLConnection與HttpClient的使用與封裝
- Android中使用HttpURLConnection實現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片
- Android通過HttpURLConnection和HttpClient接口實現(xiàn)網(wǎng)絡(luò)編程
- Golang+Android基于HttpURLConnection實現(xiàn)的文件上傳功能示例
- Android開發(fā)使用HttpURLConnection進行網(wǎng)絡(luò)編程詳解【附源碼下載】
- android 網(wǎng)絡(luò)編程之網(wǎng)絡(luò)通信幾種方式實例分享
- Android網(wǎng)絡(luò)編程之UDP通信模型實例
相關(guān)文章
ExpandableListView實現(xiàn)簡單二級列表
這篇文章主要為大家詳細介紹了ExpandableListView實現(xiàn)簡單二級列表,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11Android簡單實現(xiàn)動態(tài)權(quán)限獲取相機權(quán)限及存儲空間等多權(quán)限
這篇文章主要介紹了Android簡單實現(xiàn)動態(tài)權(quán)限獲取相機權(quán)限及存儲空間等多權(quán)限,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-07-07詳解如何在Flutter中用小部件創(chuàng)建響應(yīng)式布局
由于Flutter的跨平臺、單一代碼庫的能力,了解屏幕管理以防止像柔性溢出錯誤或糟糕的用戶界面設(shè)計這樣的問題是至關(guān)重要的。本文將探討如何用靈活和擴展的小部件創(chuàng)建響應(yīng)式布局,需要的可以參考一下2022-02-02利用smsmanager實現(xiàn)后臺發(fā)送短信示例
這篇文章主要介紹了android利用SmsManager可以實現(xiàn)后臺發(fā)送短信的方法,最近有使用說明,大家可以參考使用2014-01-01