0912Android基础网络技术之Http协议访问网络
2015-09-14 22:06
567 查看
使用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>