HttpURLConnection訪問方式:
首先需要獲取到HttpURLConnection的實例,一般需要new 一個URL並且傳入訪問地址,然後調用openConncetion()
URL url=new URL("https://www.baidu.com");
HttpURLConnection http= (HttpURLConnection) url.openConnection();
然後從服務器獲得數據是GET:
http.setRequestMethod("GET");
可以設置連接超時還有讀取超時
http.setConnectTimeout(8000); http.setReadTimeout(8000);
調用getIuputStream()就可以獲得字符流
InputStream in=http.getInputStream();
最後調用:disconnect();進行網絡訪問關閉。
例子:獲得百度首頁:
xlm佈局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.zobject.http.MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="10dp" android:layout_marginStart="10dp" android:text="Button" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </ScrollView> </RelativeLayout>
java代碼:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ TextView result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button= (Button) findViewById(R.id.button); result= (TextView) findViewById(R.id.textView); button.setOnClickListener(this); } @Override public void onClick(View view) { if (view.getId()==R.id.button){ getresult(); } } private void getresult() { new Thread(new Runnable() { @Override public void run() { HttpURLConnection http=null; BufferedReader read=null; try { URL url=new URL("https://www.baidu.com"); http= (HttpURLConnection) url.openConnection(); http.setRequestMethod("GET"); http.setConnectTimeout(8000); http.setReadTimeout(8000); InputStream in=http.getInputStream(); read=new BufferedReader(new InputStreamReader(in)); StringBuilder res=new StringBuilder(); String line; while ((line=read.readLine())!=null){ res.append(line); } showresult(res.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (read!=null){ try { read.close(); } catch (IOException e) { e.printStackTrace(); } } if (http!=null){ http.disconnect(); } } } }).start(); } private void showresult(final String string) { runOnUiThread(new Runnable() {//切換到主線程進行ui更新 @Override public void run() { result.setText(string); } }); } }
結果截圖:用okhttp進行網絡訪問:
okhttp是一個開源網絡通信庫,使用它可以讓我們節省很多的時間:
首先使用okhttp需要添加依賴包:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
使用首先要創建一個okhttp的實例
OkHttpClient client = new OkHttpClient();
發起請求需要創建一個Requst的實例:
Request request = new Request.Builder().build();
之後需要創建一個newcall對象並且調用execute方法獲得服務器的數據:
Response response = client.newCall(request).execute();response攜帶有數據可以通過以下方法獲得數據:
String res = response.body().string();
同樣的實例獲取百度首頁:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { TextView result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); result = (TextView) findViewById(R.id.textView); button.setOnClickListener(this); } @Override public void onClick(View view) { if (view.getId() == R.id.button) { getresult(); } } private void getresult() { new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("https://www.baidu.com").build(); try { Response response = client.newCall(request).execute(); String res = response.body().string(); showresult(res); } catch (IOException e) { e.printStackTrace(); } } }).start(); } private void showresult(final String string) { runOnUiThread(new Runnable() { @Override public void run() { result.setText(string); } }); } }可以看到代碼精簡了很多。這裏只是簡單的實現和使用。後續進行深入的學習。效果是一樣的都是獲得百度首頁的文件流,就不貼圖了。