Android使用URLConnection提交請求的實現(xiàn)
URL的openConnection()方法將返回一個URLConnection對象,該對象表示應(yīng)用程序和URL之間的通信連接。程序可以通過URLConnection實例向該URL發(fā)送請求,讀取URL引用的資源。
通常創(chuàng)建一個和URL的連接,并發(fā)送請求、讀取此URL引用的資源需要如下幾個步驟:
Step1: 通過調(diào)用URL對象的openConnection()方法來創(chuàng)建URLConnection對象;
Step2:設(shè)置URLConnection的參數(shù)和普通請求屬性;
Step3:如果只是發(fā)送GET方式的請求,那么使用connect方法建立和遠程資源之間的實際連接即可;如果需要發(fā)送POST方式的請求,則需要獲取URLConnection實例對應(yīng)的輸出流來發(fā)送請求參數(shù);
Step4:遠程資源變?yōu)榭捎?,程序可以訪問遠程資源的頭字段,或通過流入流讀取遠程資源的數(shù)據(jù)。
下面的程序Demo示范了如何向Web站點發(fā)送GET請求、POST請求,并從Web站點取得響應(yīng)。該程序中用到一個GET、POST請求的工具類,該類代碼如下:
GetPostUtil.java邏輯代碼如下:
package com.fukaimei.getposttest;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* Created by FuKaimei on 2017/10/2.
*/
public class GetPostUtil {
private static final String TAG = "GetPostUtil";
/**
* 向指定URL發(fā)送GET方式的請求
*
* @param url 發(fā)送請求的URL
* @param params 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1 & name2=value2的形式
* @return URL所代表遠程資源的響應(yīng)
*/
public static String sendGet(String url, String params) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(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.connect();
// 獲取所有的響應(yīng)頭字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍歷所有的響應(yīng)頭字段
for (String key : map.keySet()) {
Log.d(TAG, key + "---->" + map.get(key));
}
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
Log.d(TAG, "發(fā)送GET請求出現(xiàn)異常!" + e);
e.printStackTrace();
} finally { // 使用finally塊來關(guān)閉輸入流
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 向指定URL發(fā)送POST方式的請求
*
* @param url 發(fā)送請求的URL
* @param params 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1 & name2=value2的形式
* @return 所代表遠程資源的響應(yīng)
*/
public static String sendPost(String url, String params) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(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)");
// 發(fā)送POST請求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應(yīng)的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
out.print(params);
// flush輸出流的緩存
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
Log.d(TAG, "發(fā)送POST請求出現(xiàn)異常!" + e);
e.printStackTrace();
} finally { // 使用finally塊來關(guān)閉輸出流、輸入流
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
從上面的程序Demo可以看出,如果需要發(fā)送GET請求,只要調(diào)用URLConnection的connect()方法去建立實際的連接即可。如果需要發(fā)送POST請求,則需要獲取URLConnection的OutputStream,然后再向網(wǎng)絡(luò)中輸出請求參數(shù)。
提供了上面發(fā)送GET請求、POST請求的工具類之后,接下來就可以在Activity類中通過該工具類發(fā)送請求了。該程序的界面中包含兩個按鈕,一個按鈕用于發(fā)送GET請求,一個按鈕用于發(fā)送POST請求。程序還提供了一個EditText來顯示服務(wù)器的響應(yīng)。
layout/activity_main.xml界面布局代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="發(fā)送GET請求" />
<Button
android:id="@+id/post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="發(fā)送POST請求" />
</LinearLayout>
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff"
android:gravity="top"
android:textColor="#f000"
android:textSize="16sp" />
</LinearLayout>
MainActivity.java邏輯代碼如下:
package com.fukaimei.getposttest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button get, post;
TextView show;
// 代表服務(wù)器響應(yīng)的字符串
String response;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
// 設(shè)置show控件服務(wù)器響應(yīng)
show.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get = (Button) findViewById(R.id.get);
post = (Button) findViewById(R.id.post);
show = (TextView) findViewById(R.id.show);
get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
response = GetPostUtil.sendGet("https://www.mi.com/", null);
// 發(fā)送消息通知UI線程更新UI組件
handler.sendEmptyMessage(0x123);
}
}.start();
}
});
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
response = GetPostUtil.sendPost("http://172.xx.xx.xxx:8080/fukaimei/login.jsp", "name=android&pass=123");
}
}.start();
// 發(fā)送消息通知UI線程更新UI組件
handler.sendEmptyMessage(0x123);
}
});
}
}
上面程序Demo中用于發(fā)送GET請求、POST請求。從上面的代碼可以發(fā)現(xiàn),借助于URLConnection類的幫助,應(yīng)用程序可以非常方便地與指定站點交換信息,包括發(fā)送GET請求、POST請求,并獲取網(wǎng)站的響應(yīng)等。
注意:由于該程序需要訪問互聯(lián)網(wǎng),因此還需要在清單文件AndroidManifest.xml文件中授權(quán)訪問互聯(lián)網(wǎng)的權(quán)限:
<!-- 授權(quán)訪問互聯(lián)網(wǎng)--> <uses-permission android:name="android.permission.INTERNET" />
Demo程序運行效果界面截圖如下:


以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- 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通信模型實例
- Android開發(fā)使用URLConnection進行網(wǎng)絡(luò)編程詳解
相關(guān)文章
flutter BottomAppBar實現(xiàn)不規(guī)則底部導航欄
這篇文章主要為大家詳細介紹了flutter BottomAppBar實現(xiàn)不規(guī)則底部導航欄,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Android TextView中文本點擊文字跳轉(zhuǎn) (代碼簡單)
用過微博Android手機端的朋友的都知道微博正文有時有一些高亮顯示的文本,如話題、提到的人等等,當點擊這些文本時會跳到另外一個頁面(即另一個activity),下面就要來模仿微博的這個功能2016-01-01
Android那兩個你碰不到但是很重要的類之ViewRootImpl
這兩個類就是ActivityThread和ViewRootImpl,之所以說碰不到是因為我們無法通過正常的方式引用這兩個類或者其類的對象,本文就嘗試從幾個我們經(jīng)常接觸的方面先談?wù)刅iewRootImpl,感興趣的可以參考閱讀下2023-05-05
Android Intent傳遞數(shù)據(jù)大小限制詳解
這篇文章主要給大家介紹了關(guān)于Android Intent傳遞數(shù)據(jù)大小限制的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對各位Android開發(fā)者們具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04
Android實現(xiàn)打開手機淘寶并自動識別淘寶口令彈出商品信息功能
最近項目經(jīng)理給我們安排一個活兒,基于Android開發(fā)實現(xiàn)打開手機淘寶,并自動識別淘口令,彈出商品信息,今天小編就抽空給大家分享下這個需求是怎么實現(xiàn)的,需要的朋友參考下吧2017-11-11

