Android開發(fā)使用URLConnection進(jìn)行網(wǎng)絡(luò)編程詳解
本文實(shí)例講述了Android開發(fā)使用URLConnection進(jìn)行網(wǎng)絡(luò)編程。分享給大家供大家參考,具體如下:
URL的openConnection()
方法將返回一個(gè)URLConnection,該對(duì)象表示應(yīng)用程序和URL之間的通信連接,程序可以通過(guò)URLConnection實(shí)例向該URL發(fā)送請(qǐng)求,讀取URL引用的資源。通常創(chuàng)建一個(gè)和URL的連接,并發(fā)送請(qǐng)求,讀取此URL引用的資源。
需要如下步驟:
a)通過(guò)調(diào)用URL對(duì)象openConnection()
方法來(lái)創(chuàng)建URLConnection對(duì)象
b)設(shè)置URLConnection的參數(shù)和普通請(qǐng)求屬性
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請(qǐng)求必須設(shè)置如下兩行
conn.setDoInput(true)
:設(shè)置該URLConnection的doInput請(qǐng)求頭字段的值
coon.setDoOutput(true)
:
c)調(diào)用connect()
:打開到此URL引用的資源的通信鏈接(如果尚未建立這樣的連接)。
如果在已打開連接(此時(shí) connected 字段的值為 true)的情況下調(diào)用 connect 方法,則忽略該調(diào)用.
URLConnection 對(duì)象經(jīng)歷兩個(gè)階段:首先創(chuàng)建對(duì)象,然后建立連接。
在創(chuàng)建對(duì)象之后,建立連接之前,可指定各種選項(xiàng)(例如doInput和UseCaches).連接后再進(jìn)行設(shè)置就會(huì)發(fā)生錯(cuò)誤。連接后才能進(jìn)行的操作(例如getContentLength),如有必要,將隱式執(zhí)行連接.
d)如果只是發(fā)送GET方式請(qǐng)求,使用connect方法建立和遠(yuǎn)程資源之間的實(shí)際連接即可,在請(qǐng)求的地址中傳入數(shù)據(jù)。
如果需要發(fā)送Post方法請(qǐng)求。需要獲取URLConnection實(shí)例對(duì)應(yīng)的輸出流來(lái)發(fā)送請(qǐng)求參數(shù),
PrintWriter out=new PrintWriter(conn.getOutputStream()); //解決亂碼問(wèn)題 String n=EncodingUtils.getString("張三".getBytes(),"UTF-8"); out.write("name="+n+"&pwd="+pwd); out.flush();//刷新輸出流的緩沖
e)遠(yuǎn)程資源變?yōu)榭捎?,程序可以訪問(wèn)遠(yuǎn)程資源的頭字段或通過(guò)輸入流讀取遠(yuǎn)程資源的數(shù)據(jù)。
getInputStream()
獲取輸入流。
從輸入流讀取response的數(shù)據(jù)。
注意:
1)如果既要使用輸入流讀取URLConnection響應(yīng)的內(nèi)容,也要使用輸出流發(fā)送請(qǐng)求參數(shù),一定要先使用輸出流,再使用輸入流。
2)借助于URLConnection類的幫助,應(yīng)用程序可以非常方便地與指定站點(diǎn)交換信息,包括發(fā)送GET請(qǐng)求,POST請(qǐng)求,并獲取網(wǎng)站的響應(yīng)等。
代碼編寫步驟如下:
1.先寫一個(gè)服務(wù)器-web工程
新建一個(gè)Servlet--LoginServlet,簡(jiǎn)單實(shí)現(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.新建一個(gè)android項(xiàng)目,在MainActivity中分別使用get方法和post方法實(shí)現(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();//字符串,都可以存儲(chǔ)和操作字符串,它是變量 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.運(yùn)行,把Tomcat打開~
效果圖如下:
附:完整實(shí)例代碼點(diǎn)擊此處本站下載。
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android開發(fā)入門與進(jìn)階教程》、《Android調(diào)試技巧與常見(jiàn)問(wèn)題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android使用URLConnection提交請(qǐng)求的實(shí)現(xiàn)
- Android HttpURLConnection.getResponseCode()錯(cuò)誤解決方法
- Android 中HttpURLConnection與HttpClient使用的簡(jiǎn)單實(shí)例
- Android中HttpURLConnection與HttpClient的使用與封裝
- Android中使用HttpURLConnection實(shí)現(xiàn)GET POST JSON數(shù)據(jù)與下載圖片
- Android通過(guò)HttpURLConnection和HttpClient接口實(shí)現(xiàn)網(wǎng)絡(luò)編程
- Golang+Android基于HttpURLConnection實(shí)現(xiàn)的文件上傳功能示例
- Android開發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程詳解【附源碼下載】
- android 網(wǎng)絡(luò)編程之網(wǎng)絡(luò)通信幾種方式實(shí)例分享
- Android網(wǎng)絡(luò)編程之UDP通信模型實(shí)例
相關(guān)文章
ExpandableListView實(shí)現(xiàn)簡(jiǎn)單二級(jí)列表
這篇文章主要為大家詳細(xì)介紹了ExpandableListView實(shí)現(xiàn)簡(jiǎn)單二級(jí)列表,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11Android簡(jiǎn)單實(shí)現(xiàn)動(dòng)態(tài)權(quán)限獲取相機(jī)權(quán)限及存儲(chǔ)空間等多權(quán)限
這篇文章主要介紹了Android簡(jiǎn)單實(shí)現(xiàn)動(dòng)態(tài)權(quán)限獲取相機(jī)權(quán)限及存儲(chǔ)空間等多權(quán)限,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07AndroidStudio項(xiàng)目制作倒計(jì)時(shí)模塊的方法
本篇文章主要介紹了AndroidStudio項(xiàng)目制作倒計(jì)時(shí)模塊的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04詳解如何在Flutter中用小部件創(chuàng)建響應(yīng)式布局
由于Flutter的跨平臺(tái)、單一代碼庫(kù)的能力,了解屏幕管理以防止像柔性溢出錯(cuò)誤或糟糕的用戶界面設(shè)計(jì)這樣的問(wèn)題是至關(guān)重要的。本文將探討如何用靈活和擴(kuò)展的小部件創(chuàng)建響應(yīng)式布局,需要的可以參考一下2022-02-02Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序示例
這篇文章主要介紹了Android實(shí)現(xiàn)的簡(jiǎn)單藍(lán)牙程序,結(jié)合實(shí)例形式分析了Android藍(lán)牙程序的原理與客戶端、服務(wù)器端具體實(shí)現(xiàn)步驟,需要的朋友可以參考下2016-10-10利用smsmanager實(shí)現(xiàn)后臺(tái)發(fā)送短信示例
這篇文章主要介紹了android利用SmsManager可以實(shí)現(xiàn)后臺(tái)發(fā)送短信的方法,最近有使用說(shuō)明,大家可以參考使用2014-01-01Android listview的滑動(dòng)沖突解決方法
這篇文章主要介紹了Android listview的滑動(dòng)沖突解決方法的相關(guān)資料,需要的朋友可以參考下2017-02-02