知識
不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側(cè)重于功能的便捷,營銷的便利,運營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!
android學(xué)習(xí)二十(使用HTTP協(xié)議訪問網(wǎng)絡(luò))
發(fā)表時間:2020-10-19
發(fā)布人:葵宇科技
瀏覽次數(shù):64
應(yīng)用HttpURLConnection
在Android上發(fā)送HTTP請求的方法一般有兩種,HttpURLConnection和HttpClient,如今先進(jìn)修下
HttpURLConnection的用法。
接下來就可以進(jìn)行一些自由的定制了,比瘸黎置連接超時,攫取超時的毫秒數(shù),以及辦事器欲望獲得的一些消息優(yōu)等。這部分內(nèi)容根據(jù)本身的實際情況進(jìn)行編寫,示例如下:
起首須要獲取到HttpURLConnection的實例,一般只需new 出一個URL對象,并傳入目標(biāo)收集的地址,然后
URL URL=new URL("http://www.baidu.com");
HttpURLConnection connection=( HttpURLConnection)url.openConnection();
獲得了 HttpURLConnection的實例之后,我們可以設(shè)置一下HTTP請求所應(yīng)用的辦法。常用的辦法重要有兩個,
connection.setRequestMethod("GET");
connection.setConnectionTimeout(8000);
connection.setReadTimeout(8000);
之后調(diào)用getInputStream()辦法就可以獲取到辦事器返回的輸入流了,剩下的義務(wù)就是對輸入流進(jìn)行攫取,如下所示:
InputStream in=connection.getInputStream();
最后可聲調(diào)用disconnect()辦法將這個HTTP連接封閉掉落,如下所示:
connection.disconnection();
只須要在轉(zhuǎn)換的時刻將字符集指定成utf-8就可以了,如下所示:
//要乞降響應(yīng)都成功了
下面經(jīng)由過程一個具體的例子來熟悉下HttpURLConnection的用法。新建NetworkTest項目,起首修改activit_main.xml中的代碼,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/send_request" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="send request" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/response_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
因為手機(jī)屏幕的空間一般都比較小,有些時刻過多的內(nèi)容一屏是顯示不下的,借助ScrollView控件的話就可以許可我們以滾動的情勢查看屏幕外的那部分內(nèi)容。別的構(gòu)造中還放置了一個Button和一個TextView,Button用來發(fā)送HTTP請求,TextView用于將辦事器返回的數(shù)據(jù)顯示出來。接著修改MainActivity中的代碼如下所示:
在send request按鈕的點擊事沂攀里調(diào)用了sendRequestWithHttpURLConnection()辦法,,在這個辦法中先是開啟了一個子線程,然后在子線程里應(yīng)用HttpURLConnection發(fā)出一條HTTP請求,請求的目標(biāo)地址就是百度的首頁。接著應(yīng)用BufferedReader對辦事器返回的流進(jìn)行攫取,并將結(jié)不雅存放到了一個Message對象中。這里為什么要應(yīng)用Message對象呢?當(dāng)然是因為子線程中無法對ui進(jìn)行操作了。我們欲望可以將辦事器返回的內(nèi)容顯示到界面上所以就創(chuàng)建了一個Message對象,并應(yīng)用Handler將它發(fā)送出去。之后又在Handler的handMessage()辦法中對這條Message進(jìn)行處理,最終掏出結(jié)不雅并設(shè)置到TextView上。
在開端運行之前,還須要聲明一下收集權(quán)限。修改AndroidManifest.xml中的代碼,如下所示:
if(httpResponse.getStatusCode()==200){
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jack.networktest" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET"/> <uses-sdk android:minSdkVersion="13" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.jack.networktest.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
運行下法度榜樣,點擊send request按鈕,結(jié)不雅如下所示:
[img]http://img.blog.csdn.net/20150106162434587?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
辦事器返回給我們的就是這種HTML代碼,只是平日情況下瀏覽器都邑將這些代碼解析成漂亮的網(wǎng)頁后再展示出來。
如不雅想要提交數(shù)據(jù)給辦事器,只須要將HTTP請求的辦法改成POST,并在獲取輸入流之前把 要提交的數(shù)據(jù)寫出來即可。留意每條數(shù)據(jù)都要以鍵值對的情勢存在,數(shù)據(jù)與數(shù)據(jù)之間用&符號隔開,比如說我們想要向辦事器提交用戶名和暗碼,就可以如許寫:
connection.setRequestMethod("POST");
package com.jack.networktest; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /* 在Android上發(fā)送HTTP請求的方法一般有兩種,HttpURLConnection和HttpClient,如今先進(jìn)修下 HttpURLConnection的用法。 起首須要獲取到HttpURLConnection的實例,一般只需new 出一個URL對象,并傳入目標(biāo)收集的地址,然后 調(diào)用一下openConnection()辦法即可,如下所示: URL URL=new URL("http://www.baidu.com"); HttpURLConnection connection=( HttpURLConnection)url.openConnection(); 獲得了 HttpURLConnection的實例之后,我們可以設(shè)置一下HTTP請求所應(yīng)用的辦法。常用的辦法重要有兩個, get和post。get表示欲望大年夜辦事器那邊獲取數(shù)據(jù),而post則表示提交數(shù)據(jù)給辦事器。寫法如下: connection.setRequestMethod("GET"); 接下來就可以進(jìn)行一些自由的定制了,比瘸黎置連接超時,攫取超時的毫秒數(shù),以及辦事器欲望獲得的一些消息優(yōu)等。 這部分內(nèi)容根據(jù)本身的實際情況進(jìn)行編寫,示例如下: connection.setConnectionTimeout(8000); connection.setReadTimeout(8000); 之后調(diào)用getInputStream()辦法就可以獲取到辦事器返回的輸入流了,剩下的義務(wù)就是對輸入流進(jìn)行攫取,如下所示: InputStream in=connection.getInputStream(); 最后可聲調(diào)用disconnect()辦法將這個HTTP連接封閉掉落,如下所示: connection.disconnection(); 下面經(jīng)由過程一個具體的例子來熟悉下HttpURLConnection的用法。新建NetworkTest項目,起首修改activit_main.xml中的代碼,如下所示: */ public class MainActivity extends Activity implements OnClickListener{ public static final int SHOW_RESPONSE=0; private Button sendRequest=null; private TextView responseText=null; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch(msg.what){ case SHOW_RESPONSE: String response=(String) msg.obj; //在這里進(jìn)行UI操作,將結(jié)不雅顯示到界面上 responseText.setText(response); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendRequest=(Button) findViewById(R.id.send_request); responseText=(TextView) findViewById(R.id.response_text); sendRequest.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("MainActivity", "onClick(View v)!"); if(v.getId()==R.id.send_request){ sendRequestWithHttpURLConnection(); } } private void sendRequestWithHttpURLConnection(){ //開啟線程來提議收集請求 new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection=null; try { URL url=new URL("http://www.baidu.com"); connection =(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in=connection.getInputStream(); //下面對獲取到的輸入流進(jìn)行攫取 BufferedReader reader=new BufferedReader(new InputStreamReader(in)); StringBuilder response=new StringBuilder(); String line; while((line=reader.readLine())!=null){ response.append(line); } Message message=new Message(); message.what=SHOW_RESPONSE; //將辦事器返回的結(jié)不雅存放到Message中 message.obj=response.toString(); handler.sendMessage(message); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ if(connection!=null){ connection.disconnect(); } } } }).start(); } }
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
應(yīng)用HttpClient
調(diào)用一下openConnection()辦法即可,如下所示:
<span style="font-size:18px;"> HttpClient是Apache供給的HTTP收集拜訪接口,大年夜一開端的時刻就被惹人到android的api中。它可以 完成和HttpURLConnection幾乎一模一樣的效不雅,但兩者的之間的用法卻竽暌剮較大年夜的差別,下面我們看看HttpClient的用法。 起首我們要知道,HttpClient是一個接口,是以無法創(chuàng)建它的實例,平日情況下都邑創(chuàng)建一個DefaultHttpClient的實例,如下所示: HttpClient httpClient=new DefaultHttpClient(); 接下來如不雅想要提議一條GET請求,就可以創(chuàng)建一個HttpGet對象,并傳入目標(biāo)的收集地址,然后調(diào)用HttpClient的execute()辦法即可: HttpGet httpGet=new HttpGet("http://www.baidu.com"); httpClient.execute(httpGet); 如不雅是提議一條POST請求會比GET稍復(fù)雜一點,我們須要創(chuàng)建一個HttpPost對象,并傳入目標(biāo)收集地址,如下所示: HttpPost httpPost=new HttpPost("http://www.baidu.com"); 然后經(jīng)由過程一個NameValuePair集合來存放待提交的參數(shù),并將這個參數(shù)集合傳入到一個UrlEncodedFormEntity中,然后 調(diào)用HttpPost的setEntity()辦法將構(gòu)建好的UrlEncodedFormEntity傳入,如下所示: List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username","jack")); params.add(new BasicNameValuePair("password","123456")); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8"); httpPost.setEntity(entity); 接下來的操作就和HttpGet一樣了,調(diào)用HttpClient的execute()辦法,并將HttpPost對象傳入即可: httpClient.execute(httpPost); 履行execute()辦法之后會返回一個HttpResponse對象,辦事器所返回的所有信息就會包含在這瑯綾擎。平日情況下我們都邑先掏出辦事器返回的狀況 碼,如不雅等于200就解釋要乞降響應(yīng)都成功了,如下所示: if(httpResponse.getStatusCode()==200){ //要乞降響應(yīng)都成功了 } 接下來在這個if斷定的內(nèi)部掏出辦事返回的具體內(nèi)容,可聲調(diào)用getEntity()辦法獲取到一個HttpEntity實例,然后再用 EntityUtils.toString()這個靜態(tài)辦法將HttpEntity轉(zhuǎn)化成字符串即可,如下所示: HttpEntity entity=httpResponse.getEntity(); String response=EntityUtils.toString(entity); 留意如不雅辦事器返回的數(shù)據(jù)是帶中文的,直接調(diào)用EntityUtils.toString()辦法進(jìn)行轉(zhuǎn)換會有亂碼的情況出現(xiàn),這個時刻 只須要在轉(zhuǎn)換的時刻將字符集指定成utf-8就可以了,如下所示: String response=EntityUtils.toString(entity,"utf-8");</span>
HttpClient是Apache供給的HTTP收集拜訪接口,大年夜一開端的時刻就被惹人到android的api中。它可以
完成和HttpURLConnection幾乎一模一樣的效不雅,但兩者的之間的用法卻竽暌剮較大年夜的差別,下面我們看看HttpClient的用法。
起首我們要知道,HttpClient是一個接口,是以無法創(chuàng)建它的實例,平日情況下都邑創(chuàng)建一個DefaultHttpClient的實例,如下所示:
HttpClient httpClient=new DefaultHttpClient();
接下來如不雅想要提議一條GET請求,就可以創(chuàng)建一個HttpGet對象,并傳入目標(biāo)的收集地址,然后調(diào)用HttpClient的execute()辦法即可:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);
如不雅是提議一條POST請求會比GET稍復(fù)雜一點,我們須要創(chuàng)建一個HttpPost對象,并傳入目標(biāo)收集地址,如下所示:
HttpPost httpPost=new HttpPost("http://www.baidu.com");
然后經(jīng)由過程一個NameValuePair集合來存放待提交的參數(shù),并將這個參數(shù)集合傳入到一個UrlEncodedFormEntity中,然后
調(diào)用HttpPost的setEntity()辦法將構(gòu)建好的UrlEncodedFormEntity傳入,如下所示:
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","jack"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
get和post。get表示欲望大年夜辦事器那邊獲取數(shù)據(jù),而post則表示提交數(shù)據(jù)給辦事器。寫法如下:
接下來的操作就和HttpGet一樣了,調(diào)用HttpClient的execute()辦法,并將HttpPost對象傳入即可:
httpClient.execute(httpPost);
履行execute()辦法之后會返回一個HttpResponse對象,辦事器所返回的所有信息就會包含在這瑯綾擎。平日情況下我們都邑先掏出辦事器返回的狀況
}
接下來在這個if斷定的內(nèi)部掏出辦事返回的具體內(nèi)容,可聲調(diào)用getEntity()辦法獲取到一個HttpEntity實例,然后再用
EntityUtils.toString()這個靜態(tài)辦法將HttpEntity轉(zhuǎn)化成字符串即可,如下所示:
HttpEntity entity=httpResponse.getEntity();
以上就是HttpURLConnection的根本用法了,下面持續(xù)講解別的一個辦法。
String response=EntityUtils.toString(entity);
留意如不雅辦事器返回的數(shù)據(jù)是帶中文的,直接調(diào)用EntityUtils.toString()辦法進(jìn)行轉(zhuǎn)換會有亂碼的情況出現(xiàn),這個時刻
String response=EntityUtils.toString(entity,"utf-8");
碼,如不雅等于200就解釋要乞降響應(yīng)都成功了,如下所示:
接下來把NetworkTest這個項目改用HttpClient的方法再來實現(xiàn)一遍。
構(gòu)造部分完全不消修改,所以如今直接修改MainActivity中的代碼,如下所示:
package com.jack.networktest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ public static final int SHOW_RESPONSE=0; private Button sendRequest=null; private TextView responseText=null; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch(msg.what){ case SHOW_RESPONSE: String response=(String) msg.obj; //在這里進(jìn)行UI操作,將結(jié)不雅顯示到界面上 responseText.setText(response); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendRequest=(Button) findViewById(R.id.send_request); responseText=(TextView) findViewById(R.id.response_text); sendRequest.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("MainActivity", "onClick(View v)!"); if(v.getId()==R.id.send_request){ //sendRequestWithHttpURLConnection(); sendRequestWithHttpClient(); } } private void sendRequestWithHttpURLConnection(){ //開啟線程來提議收集請求 new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection=null; try { URL url=new URL("http://www.baidu.com"); connection =(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in=connection.getInputStream(); //下面對獲取到的輸入流進(jìn)行攫取 BufferedReader reader=new BufferedReader(new InputStreamReader(in)); StringBuilder response=new StringBuilder(); String line; while((line=reader.readLine())!=null){ response.append(line); } Message message=new Message(); message.what=SHOW_RESPONSE; //將辦事器返回的結(jié)不雅存放到Message中 message.obj=response.toString(); handler.sendMessage(message); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ if(connection!=null){ connection.disconnect(); } } } }).start(); } private void sendRequestWithHttpClient(){ new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ HttpClient httpClient=new DefaultHttpClient() ; HttpGet httpGet=new HttpGet("http://www.baidu.com"); HttpResponse httpResponse=httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode()==200){ //要乞降響應(yīng)都成功了 HttpEntity entity=httpResponse.getEntity(); String response=EntityUtils.toString(entity,"utf-8"); Message message=new Message(); message.what=SHOW_RESPONSE; //將辦事器返回的結(jié)不雅存放到Message中 message.obj=response.toString(); handler.sendMessage(message); } }catch(Exception e){ e.printStackTrace(); } } }).start(); } }
膳綾擎的代碼只是添加了一個sendRequestWithHttpClient()辦法,并在send request按鈕的點擊事沂攀里去調(diào)用這個辦法。在這個辦法中同樣照樣先開啟一個子線程,然后在子線程里應(yīng)用HttpClient發(fā)出一條HTTP請求,請求的目標(biāo)地址照樣百度的首頁。然后將辦事器返回的數(shù)據(jù)存放到Message對象中,并用Handler將Message發(fā)送出去。
如今從新運行法度榜樣,點擊send request按鈕,你會發(fā)明和膳綾擎的結(jié)不雅一樣,由此證實,應(yīng)用HttpClient來發(fā)送Http請求的功能也已經(jīng)實現(xiàn)了。
經(jīng)由膳綾擎的演習(xí),應(yīng)當(dāng)把HttpURLConnection 和 HttpClient的根本用法控制的差不多了。
http://blog.csdn.net/j903829182/article/details/42440155
相關(guān)案例查看更多
相關(guān)閱讀
- 昆明小程序公司
- 小程序表單
- 云南網(wǎng)站建設(shè)哪家強(qiáng)
- 昆明小程序開發(fā)聯(lián)系方式
- 汽車拆解系統(tǒng)
- 汽車報廢管理
- 云南網(wǎng)站維護(hù)
- painter
- 專業(yè)網(wǎng)站建設(shè)公司
- 做小程序被騙
- 云南做軟件
- 人口普查小程序
- 網(wǎng)站建設(shè)服務(wù)公司
- web前端
- 小程序密鑰
- 云南建設(shè)廳官方網(wǎng)站
- 網(wǎng)站收錄
- 報廢車
- 旅游網(wǎng)站建設(shè)
- 百度小程序
- 云南網(wǎng)站建設(shè)
- 網(wǎng)站優(yōu)化哪家好
- 網(wǎng)站建設(shè)首選
- 云南小程序設(shè)計
- 昆明網(wǎng)絡(luò)公司
- 云南網(wǎng)站建設(shè)服務(wù)公司
- 前端技術(shù)
- 云南網(wǎng)絡(luò)推廣
- 昆明小程序定制開發(fā)
- 政府網(wǎng)站建設(shè)服務(wù)