Android開發(fā)使用URLConnection進行網(wǎng)絡編程詳解
本文實例講述了Android開發(fā)使用URLConnection進行網(wǎng)絡編程。分享給大家供大家參考,具體如下:
URL的openConnection()方法將返回一個URLConnection,該對象表示應用程序和URL之間的通信連接,程序可以通過URLConnection實例向該URL發(fā)送請求,讀取URL引用的資源。通常創(chuàng)建一個和URL的連接,并發(fā)送請求,讀取此URL引用的資源。
需要如下步驟:
a)通過調(diào)用URL對象openConnection()方法來創(chuàng)建URLConnection對象
b)設置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請求必須設置如下兩行
conn.setDoInput(true):設置該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).連接后再進行設置就會發(fā)生錯誤。連接后才能進行的操作(例如getContentLength),如有必要,將隱式執(zhí)行連接.
d)如果只是發(fā)送GET方式請求,使用connect方法建立和遠程資源之間的實際連接即可,在請求的地址中傳入數(shù)據(jù)。
如果需要發(fā)送Post方法請求。需要獲取URLConnection實例對應的輸出流來發(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響應的內(nèi)容,也要使用輸出流發(fā)送請求參數(shù),一定要先使用輸出流,再使用輸入流。
2)借助于URLConnection類的幫助,應用程序可以非常方便地與指定站點交換信息,包括發(fā)送GET請求,POST請求,并獲取網(wǎng)站的響應等。
代碼編寫步驟如下:
1.先寫一個服務器-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)絡連接
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();
//必須設置
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();//真正的建立網(wǎng)絡連接
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打開~
效果圖如下:

附:完整實例代碼點擊此處本站下載。
更多關于Android相關內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結》、《Android開發(fā)入門與進階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
- 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)絡編程
- Golang+Android基于HttpURLConnection實現(xiàn)的文件上傳功能示例
- Android開發(fā)使用HttpURLConnection進行網(wǎng)絡編程詳解【附源碼下載】
- android 網(wǎng)絡編程之網(wǎng)絡通信幾種方式實例分享
- Android網(wǎng)絡編程之UDP通信模型實例
相關文章
基于Android實現(xiàn)保存圖片到本地并可以在相冊中顯示出來
App應用越來越人性化,不僅界面優(yōu)美而且服務也很多樣化,操作也非常方便。通過本篇文章給大家介紹基于Android實現(xiàn)保存圖片到本地并可以在相冊中顯示出來,對android保存圖片相關知識感興趣的朋友一起學習吧2015-12-12
解決android 顯示內(nèi)容被底部導航欄遮擋的問題
今天小編就為大家分享一篇解決android 顯示內(nèi)容被底部導航欄遮擋的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Android 接收推送消息跳轉(zhuǎn)到指定頁面的方法
這篇文章主要介紹了Android 接收推送消息跳轉(zhuǎn)到指定頁面的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
Android Studio 3.6中新的視圖綁定工具ViewBinding 用法詳解
這篇文章主要介紹了Android Studio 3.6中新的視圖綁定工具ViewBinding 用法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
Android自定義ImageView實現(xiàn)點擊兩張圖片切換效果
這篇文章主要為大家詳細介紹了Android自定義ImageView實現(xiàn)點擊兩張圖片切換效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12

