Android使用Http協議訪問網絡——HttpURLConnection
套路篇
使用HttpURLConnection訪問網絡一般有如下的套路:
1.獲取到HttpURLConnection的實例,new出一個URL對象,並傳入目標的網址,然後調用一下openConnection()方法。
1 HttpURLConnection connection=null; 2 URL url=new URL("http://www.baidu.com"); 3 connection=(HttpURLConnection)url.openConnection();
2.得到了HttpURLConnection的實例後,設置請求所用的方法(GET:從服務器獲取數據,POST:提交數據給服務器)
1
|
connection.setRequestMethod( "GET" );或 |
connection.setRequestMethod("POST");
3.自由定製的環節(設置連接超時,讀取的毫秒數,以及服務器希望得到的消息頭等)
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
4.利用getInputStream()方法獲取服務器的返回的輸入流,然後讀取
1
2
3
4
5
6
7
8
|
InputStream in=connection.getInputStream(); //下面對獲取到的輸入流進行讀取 BufferedReader bufr= new BufferedReader( new InputStreamReader(in)); StringBuilder response= new StringBuilder(); String line= null ; while ((line=bufr.readLine())!= null ){ response.append(line); } |
5.調用disconnect()方法將HTTP連接關閉掉
if(connection!=null){ connection.disconnect(); }
實戰篇
新建一個Android工程
1.activity_main.xml(裏面有一個Button和一個TextView)
<?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"> <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>
2.MainActivity
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; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int SHOW_RESPONSE=0;//用於更新操作 private Button sendRequest; private TextView responseText; //用於處理和發送消息的Hander private Handler handler=new Handler(){ public void handleMessage(Message msg){ //如果返現msg.what=SHOW_RESPONSE,則進行制定操作,如想進行其他操作,則在子線程裏將SHOW_RESPONSE改變 switch (msg.what){ case SHOW_RESPONSE: String response=(String)msg.obj; //進行UI操作,將結果顯示到界面上 responseText.setText(response); } } }; @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 void onClick(View v) { if(v.getId()==R.id.send_request){ sendRequestWithHttpURLConnection(); } } private void sendRequestWithHttpURLConnection(){ //開啓線程來發起網絡請求 new Thread(new Runnable() { @Override public void run() { 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(); //下面對獲取到的輸入流進行讀取 BufferedReader bufr=new BufferedReader(new InputStreamReader(in)); StringBuilder response=new StringBuilder(); String line=null; while((line=bufr.readLine())!=null){ response.append(line); } Message message=new Message(); message.what=SHOW_RESPONSE; //將服務器返回的數據存放到Message中 message.obj=response.toString(); handler.sendMessage(message); }catch(Exception e){ e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); } }
3.AndroidManifest.xml中註冊權限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
好,這個簡單的例子就弄完了,接下來就看看效果吧。
這樣我們就可以看到服務器返回給我們的數據了。