使用HTTP協議訪問網絡
它的工作原始,客戶端向服務器發出一條HTTP請求,服務器收到請求後會返回一些數據給客戶端,然後客戶端對這些數據進行解析和處理。包含HttpUrlConnection和HttpClient
通過urlConnection讀取網頁中的數據
首先的首先還是要先添加權限
<uses-permission android:name="android.permission.INTERNET" />
設置一個按鍵觸發事件,將訪問網絡寫在線程裏,因爲訪問網絡是耗時操作,耗時操作不能直接寫在主線程裏面。
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_read:
new Thread(new Runnable() {
@Override
public void run() {
connectServerlet();
}
}).start();
break;
}
線程 connectServerlet(),將獲得的信息通過Message傳到Handler中,進而設置UI。
private void connectServerlet() {
try {
URL url = new URL("http://192.168.0.44:8080/MyServiceTest/MyTestServlet");
// URL url = new URL("http://www.360.com");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
// 新建stringbuffer對象
mStringBuffer = new StringBuffer();
while (line != null) {
mStringBuffer.append(line);
Log.d("讀取服務器的內容", " " + line);
line = reader.readLine();
}
// 將數據傳入handler
Message msg = handler.obtainMessage();
msg.what = SEND_MESSAGE;
msg.obj = mStringBuffer.toString().trim();// trim去掉空格
handler.sendMessage(msg);
reader.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler記得導這個包import android.os.Handler;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SEND_MESSAGE:
String content = (String) msg.obj;
mTvMessage.setText(content);
break;
default:
break;
}
}
};
全部代碼見主線程代碼
達到的效果
HttpURLConnection
添加權限
<uses-permission android:name="android.permission.INTERNET" />
另外開一個活動,通過intent進行通信
Intent intenthttpUrl=new Intent(getApplicationContext(),MyHttpURLConnection.class);
startActivity(intenthttpUrl);
在AndroidMainfest中註冊(具體位置見下面主線程代碼)
<activity android:name=".MyHttpURLConnection"></activity>
doget和dopost方法
package com.example.laowang.myinternet;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
public class MyHttpURLConnection extends Activity implements View.OnClickListener{
private Button mBtnHttpURlGet;
private Button mBtnHttpURlPost;
private StringBuffer mStringBuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_httpurl);
mBtnHttpURlGet= (Button) findViewById(R.id.btn_httpurl_doget);
mBtnHttpURlPost= (Button) findViewById(R.id.btn_httpurl_dopost);
mBtnHttpURlGet.setOnClickListener(this);
mBtnHttpURlPost.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_httpurl_doget:
new Thread(new Runnable() {
@Override
public void run() {
doGet();
}
}).start();
break;
case R.id.btn_httpurl_dopost:
new Thread(new Runnable() {
@Override
public void run() {
doPost();
}
}).start();
break;
default:
break;
}
}
private void doPost() {
String urlString1="http://192.168.0.44:8080/MyServiceTest/MyTestServlet";
try {
URL url1= new URL(urlString1);
HttpURLConnection connection=(HttpURLConnection) url1.openConnection();//強制轉型
//HttpURLConnection進行控制
//設置連接超時時間
connection.setConnectTimeout(30000);
//讀取超時時間
connection.setReadTimeout(30000);
//設置編碼格式
// 設置接受的數據類型
connection.setRequestProperty("Accept-Charset", "utf-8");
// 設置可以接受序例化的java對象
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//客戶端輸出部分
//設置 URL 請求的方法
connection.setRequestMethod("POST");
//設置客戶端可以給服務器提交數據,默認是false的,POST時必須改成true
connection.setDoOutput(true);
//設置可以讀取服務器返回的內容,默認爲true,不寫也可以
connection.setDoInput(true);
//post方法不允許使用緩存
connection.setUseCaches(false);
String params="username=HttpURLConnectionDoPost&password=123456";
connection.getOutputStream().write(params.getBytes());//客戶端輸出數據
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
// 新建stringbuffer對象
mStringBuffer = new StringBuffer();
while (line != null) {
mStringBuffer.append(line);
Log.d("讀取服務器的內容", " " + line);
line = reader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void doGet() {
try {
//基本設置,設置URL連接,設置HttpURLConnection
String urlString = "http://192.168.0.44:8080/MyServiceTest/MyTestServlet?username=HttpURLConnectionDoGet&password=123456";
URL url = new URL(urlString);//生成url
URLConnection connect = url.openConnection();//打開url連接
//強制造型成httpUrlConnection
HttpURLConnection httpConnection = (HttpURLConnection) connect;
//設置請求方法
httpConnection.setRequestMethod("GET");
//設置連接超時的時間
httpConnection.setConnectTimeout(3000);
//讀取時間超時
httpConnection.setReadTimeout(3000);
//設置編碼格式
// 設置接受的數據類型
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
// 設置可以接受序例化的java對象
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream is = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
// 新建stringbuffer對象
mStringBuffer = new StringBuffer();
while (line != null) {
mStringBuffer.append(line);
Log.d("讀取服務器的內容", " " + line);
line = reader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
達到的效果
doget
dopost
HttpClient
添加權限
<uses-permission android:name="android.permission.INTERNET" />
另外開一個活動,通過intent進行通信
Intent intent1 = new Intent(getApplicationContext(), MyHttpClientActivity.class);
startActivity(intent1);
在AndroidMainfest中註冊(具體位置見下面主線程代碼)
<activity android:name=".MyHttpClientActivity"></activity>
doget和dopost方法
package com.example.laowang.myinternet;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
public class MyHttpClientActivity extends Activity implements View.OnClickListener{
private Button mBtnClientDoPost;
private Button mBtnClientDoGet;
private TextView mTvClientBack;
private String line;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_httpclient);
mBtnClientDoGet= (Button) findViewById(R.id.btn_client_doget);
mBtnClientDoPost= (Button) findViewById(R.id.btn_client_dopost);
mTvClientBack= (TextView) findViewById(R.id.tv_client_back);
mBtnClientDoPost.setOnClickListener(this);
mBtnClientDoGet.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_client_doget:
new MyAsyncTask().execute();
break;
case R.id.btn_client_dopost:
new Thread(new Runnable() {
@Override
public void run() {
httpDoPost();
}
}).start();
break;
default:
break;
}
}
private void httpDoPost() {
String urlString = "http://192.168.0.44:8080/MyServiceTest/MyTestServlet";
HttpClient client=new DefaultHttpClient();
//設置客戶端輸出信息
NameValuePair pair1=new BasicNameValuePair("username", "HttpClientPost");
NameValuePair pair2=new BasicNameValuePair("password", "123456");
ArrayList<NameValuePair> array=new ArrayList<>();
array.add(pair2);
array.add(pair1);
// post方法
// 設置post方法及環境
HttpPost post = new HttpPost(urlString);
try {
//設置傳遞的參數格式
post.setEntity(new UrlEncodedFormEntity(array, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// 執行post方法法獲得服務器返回的所有數據
HttpResponse response = client.execute(post);
// 接收處理服務器返回數據
// 獲得服務器返回的表頭
StatusLine statusLine = response.getStatusLine();
// 獲得狀態碼
int code = statusLine.getStatusCode();
if (code == HttpURLConnection.HTTP_OK) {
// 獲得數據實體
HttpEntity entity = response.getEntity();
// 獲得數據的輸入流並讀入
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String ,Integer,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
HttpClient client=new DefaultHttpClient();
// 建立client
String urlString = "http://192.168.0.44:8080/MyServiceTest/MyTestServlet?username=HttpClientGet&password=123456";
// 設置get方法及環境
HttpGet get = new HttpGet(urlString);
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
try {
// 執行get方法法獲得服務器返回的所有數據
HttpResponse response = client.execute(get);
// 接收處理服務器返回數據
// 獲得服務器返回的表頭
StatusLine statusLine = response.getStatusLine();
// 獲得狀態碼
int code = statusLine.getStatusCode();
if (code == HttpURLConnection.HTTP_OK) {
// 獲得數據實體
HttpEntity entity = response.getEntity();
// 獲得數據的輸入流並讀入
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
line = br.readLine();
while (line != null) {
line = br.readLine();
}
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return "登錄成功";
}
}
}
達到的效果
doget
dopost
主線程代碼
這個主線程也用於後面的下載、XUtils、Volley中
package com.example.laowang.myinternet;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends Activity implements View.OnClickListener {
private Button mBtnRead;
private Button mBtnURLConnection;
private Button mBtnVolley;
private Button mBtnDownLoad;
private Button mBtnHttpClient;
private Button mBtnHttpUtils;
private TextView mTvMessage;
private StringBuffer mStringBuffer;
private static final int SEND_MESSAGE = 0x222;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SEND_MESSAGE:
String content = (String) msg.obj;
mTvMessage.setText(content);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnRead = (Button) findViewById(R.id.btn_read);
mBtnURLConnection = (Button) findViewById(R.id.btn_url_connection);
mBtnVolley = (Button) findViewById(R.id.btn_volley_get);
mBtnDownLoad = (Button) findViewById(R.id.btn_download);
mTvMessage = (TextView) findViewById(R.id.tv_message);
mBtnHttpClient = (Button) findViewById(R.id.btn_http_client);
mBtnHttpUtils = (Button) findViewById(R.id.btn_httputils_get);
mBtnRead.setOnClickListener(this);
mBtnURLConnection.setOnClickListener(this);
mBtnVolley.setOnClickListener(this);
mBtnDownLoad.setOnClickListener(this);
mBtnHttpClient.setOnClickListener(this);
mBtnHttpUtils.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_read:
new Thread(new Runnable() {
@Override
public void run() {
connectServerlet();
}
}).start();
break;
case R.id.btn_url_connection:
Intent intenthttpUrl=new Intent(getApplicationContext(),MyHttpURLConnection.class);
startActivity(intenthttpUrl);
break;
case R.id.btn_download:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
break;
case R.id.btn_volley_get:
Intent intentVolley = new Intent(getApplicationContext(), MyVolleyActivity.class);
startActivity(intentVolley);
break;
case R.id.btn_http_client:
Intent intent1 = new Intent(getApplicationContext(), MyHttpClientActivity.class);
startActivity(intent1);
break;
case R.id.btn_httputils_get:
Intent intentUtils = new Intent(getApplicationContext(), MyXUtils.class);
startActivity(intentUtils);
break;
default:
break;
}
}
private void connectServerlet() {
try {
URL url = new URL("http://192.168.0.44:8080/MyServiceTest/MyTestServlet");
// URL url = new URL("http://www.360.com");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
// 新建stringbuffer對象
mStringBuffer = new StringBuffer();
while (line != null) {
mStringBuffer.append(line);
Log.d("讀取服務器的內容", " " + line);
line = reader.readLine();
}
// 將數據傳入handler
Message msg = handler.obtainMessage();
msg.what = SEND_MESSAGE;
msg.obj = mStringBuffer.toString().trim();// trim去掉空格
handler.sendMessage(msg);
reader.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidMainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.laowang.myinternet">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".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>
<activity android:name=".SecondActivity"></activity>
<activity android:name=".MyHttpClientActivity"></activity>
<activity android:name=".MyVolleyActivity"></activity>
<activity android:name=".MyXUtils"></activity>
<activity android:name=".MyHttpURLConnection"></activity>
</application>
</manifest>