標籤:
套路篇
使用HttpConnection訪問網路一般有如下的套路:
1.擷取到HttpConnection的執行個體,new出一個URL對象,並傳入目標的網址,然後調用一下openConnection()方法。
1 HttpURLConnection connection=null;2 URL url=new URL("http://www.baidu.com");3 connection=(HttpURLConnection)url.openConnection();
2.得到了HttpConnection的執行個體後,佈建要求所用的方法(GET:從伺服器擷取資料,POST:提交資料給伺服器)
connection.setRequestMethod("GET");或
connection.setRequestMethod("POST");
3.自由定製的環節(設定連線逾時,讀取的毫秒數,以及伺服器希望得到的訊息頭等)
connection.setConnectTimeout(8000); connection.setReadTimeout(8000);
4.利用getInputStream()方法擷取伺服器的返回的輸入資料流,然後讀取
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>
好,這個簡單的例子就弄完了,接下來就看看效果吧。
這樣我們就可以看到伺服器返回給我們的資料了。
Android使用Http協議訪問網路——HttpConnection