編輯:關於Android編程
使用HttpURLConnection
在Android上發送HTTP請求的方式一般有兩種,HttpURLConnection和HttpClient,現在先學習下
HttpURLConnection的用法。
首先需要獲取到HttpURLConnection的實例,一般只需new 出一個URL對象,並傳入目標網絡的地址,然後
調用一下openConnection()方法即可,如下所示:
URL URL=new URL("http://www.baidu.com");
HttpURLConnection connection=( HttpURLConnection)url.openConnection();
得到了 HttpURLConnection的實例之後,我們可以設置一下HTTP請求所使用的方法。常用的方法主要有兩個,
get和post。get表示希望從服務器那裡獲取數據,而post則表示提交數據給服務器。寫法如下:
connection.setRequestMethod("GET");
接下來就可以進行一些自由的定制了,比如設置連接超時,讀取超時的毫秒數,以及服務器希望得到的一些消息頭等。這部分內容根據自己的實際情況進行編寫,示例如下:
connection.setConnectionTimeout(8000);
connection.setReadTimeout(8000);
之後調用getInputStream()方法就可以獲取到服務器返回的輸入流了,剩下的任務就是對輸入流進行讀取,如下所示:
InputStream in=connection.getInputStream();
最後可以調用disconnect()方法將這個HTTP連接關閉掉,如下所示:
connection.disconnection();
下面通過一個具體的例子來熟悉下HttpURLConnection的用法。新建NetworkTest項目,首先修改activit_main.xml中的代碼,如下所示:
由於手機屏幕的空間一般都比較小,有些時候過多的內容一屏是顯示不下的,借助ScrollView控件的話就可以允許我們以滾動的形式查看屏幕外的那部分內容。另外布局中還放置了一個Button和一個TextView,Button用來發送HTTP請求,TextView用於將服務器返回的數據顯示出來。接著修改MainActivity中的代碼如下所示:
package com.jack.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/*
在Android上發送HTTP請求的方式一般有兩種,HttpURLConnection和HttpClient,現在先學習下
HttpURLConnection的用法。
首先需要獲取到HttpURLConnection的實例,一般只需new 出一個URL對象,並傳入目標網絡的地址,然後
調用一下openConnection()方法即可,如下所示:
URL URL=new URL("http://www.baidu.com");
HttpURLConnection connection=( HttpURLConnection)url.openConnection();
得到了 HttpURLConnection的實例之後,我們可以設置一下HTTP請求所使用的方法。常用的方法主要有兩個,
get和post。get表示希望從服務器那裡獲取數據,而post則表示提交數據給服務器。寫法如下:
connection.setRequestMethod("GET");
接下來就可以進行一些自由的定制了,比如設置連接超時,讀取超時的毫秒數,以及服務器希望得到的一些消息頭等。
這部分內容根據自己的實際情況進行編寫,示例如下:
connection.setConnectionTimeout(8000);
connection.setReadTimeout(8000);
之後調用getInputStream()方法就可以獲取到服務器返回的輸入流了,剩下的任務就是對輸入流進行讀取,如下所示:
InputStream in=connection.getInputStream();
最後可以調用disconnect()方法將這個HTTP連接關閉掉,如下所示:
connection.disconnection();
下面通過一個具體的例子來熟悉下HttpURLConnection的用法。新建NetworkTest項目,首先修改activit_main.xml中的代碼,如下所示:
*/
public class MainActivity extends Activity implements OnClickListener{
public static final int SHOW_RESPONSE=0;
private Button sendRequest=null;
private TextView responseText=null;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case SHOW_RESPONSE:
String response=(String) msg.obj;
//在這裡進行UI操作,將結果顯示到界面上
responseText.setText(response);
break;
default:
break;
}
}
};
@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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("MainActivity", "onClick(View v)!");
if(v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection(){
//開啟線程來發起網絡請求
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
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 reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
Message message=new Message();
message.what=SHOW_RESPONSE;
//將服務器返回的結果存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
在開始運行之前,還需要聲明一下網絡權限。修改AndroidManifest.xml中的代碼,如下所示:
運行下程序,點擊send request按鈕,結果如下所示:

<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+ICAgICC3/s7xxve3tbvYuPjO0sPHtcS+zcrH1eLW1khUTUy0+sLro6zWu8rHzaizo8fpv/bPwuSvwMDG97a8u+G9q9Xi0Km0+sLrveLO9rPJxq/BwbXEzfjSs7rz1NnVucq+s/bAtKGjPC9wPgo8cD4gICAgICAgyOe5+8/r0qrM4b27yv2+3bj4t/7O8cb3o6zWu9Do0qq9q0hUVFDH68fztcS3vbeouMSzyVBPU1SjrLKi1Nq78cihyuTI68H31q7HsLDRINKqzOG9u7XEyv2+3dC0s/bAtLy0v8mho9ei0uLDv8z1yv2+3ba80qrS1Lz8JiMyMDU0MDu21LXE0M7KvbTm1NqjrMr9vt3T68r9vt3Wrrzk08MmYW1wO7f7usW49L+qo6yxyMjny7XO0sPHz+vSqs/yt/7O8cb3zOG9u9PDu6fD+7rNw9zC66Osvs2/ydLU1eLR+dC0o7o8YnI+CmNvbm5lY3Rpb24uc2V0UmVxdWVzdE1ldGhvZCg="POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
以上就是HttpURLConnection的基本用法了,下面繼續講解另外一個方法。
使用HttpClient
HttpClient是Apache提供的HTTP網絡訪問接口,從一開始的時候就被引入到android的api中。它可以
完成和HttpURLConnection幾乎一模一樣的效果,但兩者的之間的用法卻有較大的差別,下面我們看看HttpClient的用法。
首先我們要知道,HttpClient是一個接口,因此無法創建它的實例,通常情況下都會創建一個DefaultHttpClient的實例,如下所示:
HttpClient httpClient=new DefaultHttpClient();
接下來如果想要發起一條GET請求,就可以創建一個HttpGet對象,並傳入目標的網絡地址,然後調用HttpClient的execute()方法即可:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);
如果是發起一條POST請求會比GET稍復雜一點,我們需要創建一個HttpPost對象,並傳入目標網絡地址,如下所示:
HttpPost httpPost=new HttpPost("http://www.baidu.com");
然後通過一個NameValuePair集合來存放待提交的參數,並將這個參數集合傳入到一個UrlEncodedFormEntity中,然後
調用HttpPost的setEntity()方法將構建好的UrlEncodedFormEntity傳入,如下所示:
List params=new ArrayList();
params.add(new BasicNameValuePair("username","jack"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
接下來的操作就和HttpGet一樣了,調用HttpClient的execute()方法,並將HttpPost對象傳入即可:
httpClient.execute(httpPost);
執行execute()方法之後會返回一個HttpResponse對象,服務器所返回的所有信息就會包含在這裡面。通常情況下我們都會先取出服務器返回的狀態
碼,如果等於200就說明請求和響應都成功了,如下所示:
if(httpResponse.getStatusCode()==200){
//請求和響應都成功了
}
接下來在這個if判斷的內部取出服務返回的具體內容,可以調用getEntity()方法獲取到一個HttpEntity實例,然後再用
EntityUtils.toString()這個靜態方法將HttpEntity轉化成字符串即可,如下所示:
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);
注意如果服務器返回的數據是帶中文的,直接調用EntityUtils.toString()方法進行轉換會有亂碼的情況出現,這個時候
只需要在轉換的時候將字符集指定成utf-8就可以了,如下所示:
String response=EntityUtils.toString(entity,"utf-8"); HttpClient是Apache提供的HTTP網絡訪問接口,從一開始的時候就被引入到android的api中。它可以
完成和HttpURLConnection幾乎一模一樣的效果,但兩者的之間的用法卻有較大的差別,下面我們看看HttpClient的用法。
首先我們要知道,HttpClient是一個接口,因此無法創建它的實例,通常情況下都會創建一個DefaultHttpClient的實例,如下所示:
HttpClient httpClient=new DefaultHttpClient();
接下來如果想要發起一條GET請求,就可以創建一個HttpGet對象,並傳入目標的網絡地址,然後調用HttpClient的execute()方法即可:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);
如果是發起一條POST請求會比GET稍復雜一點,我們需要創建一個HttpPost對象,並傳入目標網絡地址,如下所示:
HttpPost httpPost=new HttpPost("http://www.baidu.com");
然後通過一個NameValuePair集合來存放待提交的參數,並將這個參數集合傳入到一個UrlEncodedFormEntity中,然後
調用HttpPost的setEntity()方法將構建好的UrlEncodedFormEntity傳入,如下所示:
List
params.add(new BasicNameValuePair("username","jack"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
接下來的操作就和HttpGet一樣了,調用HttpClient的execute()方法,並將HttpPost對象傳入即可:
httpClient.execute(httpPost);
執行execute()方法之後會返回一個HttpResponse對象,服務器所返回的所有信息就會包含在這裡面。通常情況下我們都會先取出服務器返回的狀態
碼,如果等於200就說明請求和響應都成功了,如下所示:
if(httpResponse.getStatusCode()==200){
//請求和響應都成功了
}
接下來在這個if判斷的內部取出服務返回的具體內容,可以調用getEntity()方法獲取到一個HttpEntity實例,然後再用
EntityUtils.toString()這個靜態方法將HttpEntity轉化成字符串即可,如下所示:
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);
注意如果服務器返回的數據是帶中文的,直接調用EntityUtils.toString()方法進行轉換會有亂碼的情況出現,這個時候
只需要在轉換的時候將字符集指定成utf-8就可以了,如下所示:
String response=EntityUtils.toString(entity,"utf-8");
接下來把NetworkTest這個項目改用HttpClient的方式再來實現一遍。
布局部分完全不用改動,所以現在直接修改MainActivity中的代碼,如下所示:
package com.jack.networktest;
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.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
public static final int SHOW_RESPONSE=0;
private Button sendRequest=null;
private TextView responseText=null;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case SHOW_RESPONSE:
String response=(String) msg.obj;
//在這裡進行UI操作,將結果顯示到界面上
responseText.setText(response);
break;
default:
break;
}
}
};
@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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("MainActivity", "onClick(View v)!");
if(v.getId()==R.id.send_request){
//sendRequestWithHttpURLConnection();
sendRequestWithHttpClient();
}
}
private void sendRequestWithHttpURLConnection(){
//開啟線程來發起網絡請求
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
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 reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
Message message=new Message();
message.what=SHOW_RESPONSE;
//將服務器返回的結果存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void sendRequestWithHttpClient(){
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try{
HttpClient httpClient=new DefaultHttpClient() ;
HttpGet httpGet=new HttpGet("http://www.baidu.com");
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
//請求和響應都成功了
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity,"utf-8");
Message message=new Message();
message.what=SHOW_RESPONSE;
//將服務器返回的結果存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}
上面的代碼只是添加了一個sendRequestWithHttpClient()方法,並在send request按鈕的點擊事件裡去調用這個方法。在這個方法中同樣還是先開啟一個子線程,然後在子線程裡使用HttpClient發出一條HTTP請求,請求的目標地址還是百度的首頁。然後將服務器返回的數據存放到Message對象中,並用Handler將Message發送出去。
現在重新運行程序,點擊send request按鈕,你會發現和上面的結果一樣,由此證明,使用HttpClient來發送Http請求的功能也已經實現了。
經過上面的練習,應該把HttpURLConnection 和 HttpClient的基本用法掌握的差不多了。
http://blog.csdn.net/j903829182/article/details/42440155
Memcached 源碼分析--命令流程分析
一、執行命令首先是啟動memcached 自帶參數如下: -p 設置TCP端口號(默認設置為: 11211)-U UDP監聽端口(默認:
微信讀書查看好友排名方法
打開微信讀書,點擊“我”進入個人界面; 微信讀書查看好友排名方法 點擊個人中心的好友排名,就可以進入到讀書排行榜; 微
Android的四大組建Service 簡單、易懂的解析
Service 服務:四大組件之一特性: 沒有界面運行在後台,除了界面相關的之外,Activity能做的Service也能做。service的生命周期:上圖所述一共有兩種
教你一步步實現Android微信自動搶紅包
本文介紹微信自動搶紅包的實現方法,主要實現以下幾個功能: 1.自動拆開屏幕上出現的紅包