main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/strView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/getButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用get方法發送請求"
/>
<Button
android:id="@+id/postButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用post方法發送請求"
/>
</LinearLayout>
MainActivity.java
package com.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.NameValueTable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Button getButton = null;
private Button postButton = null;
private EditText strView = null;
private String baseUrl = "http://www.baidu.com/s?";
private HttpResponse httpResponse = null;//響應對象
private HttpEntity httpEntity = null;//取出響應內容的消息對象
InputStream inputStream = null;//輸入流對象
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
strView = (EditText) findViewById(R.id.strView);
getButton = (Button) findViewById(R.id.getButton);
postButton = (Button) findViewById(R.id.postButton);
//get方法發送請求
getButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str = strView.getText().toString();
String url = baseUrl + "?wd=" + str;
//生成一個請求對象
HttpGet httpGet = new HttpGet(url);
//生成一個http客戶端對象
HttpClient httpClient = new DefaultHttpClient();
//發送請求
try {
httpResponse = httpClient.execute(httpGet);//接收響應
httpEntity = httpResponse.getEntity();//取出響應
//客戶端收到響應的信息流
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{//最後一定要關閉輸入流
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
//post方法發送請求
postButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str = strView.getText().toString();//參數
NameValuePair nameValuePair = new BasicNameValuePair("content", str);//鍵值對
//然後將鍵值對放到列表裡(類似於形成數組)
//List是一個接口,而ListArray是一個類。ListArray繼承並實現了List。所以List不能被構造,但可以向上面那樣為List創建一個引用,而ListArray就可以被構造。
//List list = new ArrayList();這句創建了一個ArrayList的對象後把上溯到了List。此時它是一個List對象了
//而ArrayList list=new ArrayList();創建一對象則保留了ArrayList的所有屬性。
//為什麼一般都使用 List list = new ArrayList() ,而不用 ArrayList alist = new ArrayList()呢? 問題就在於List有多個實現類,如 LinkedList或者Vector等等,現在你用的是ArrayList,也許哪一天你需要換成其它的實現類呢?,這時你只要改變這一行就行了:List list = new LinkedList(); 其它使用了list地方的代碼根本不需要改動。
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair);//將鍵值對放入到列表中
try {
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs);//對參數進行編碼操作
//生成一個post請求對象
HttpPost httpPost = new HttpPost(baseUrl);
httpPost.setEntity(requestHttpEntity);
//生成一個http客戶端對象
HttpClient httpClient = new DefaultHttpClient();//發送請求
try {
httpResponse = httpClient.execute(httpPost);//接收響應
httpEntity = httpResponse.getEntity();//取出響應
//客戶端收到響應的信息流
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{//最後一定要關閉輸入流
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.http"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<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>
</application>
</manifest>
注意的幾點哦:
1.get方式的參數是加在url後面的,而post方式是講參數先放到鍵值對對象中,然後將鍵值對相添加到list列表裡,然後講列表放到信息裡進行發送
2.http請求發送需要連網,故AndroidManifest.xml中要加上<uses-permission android:name="android.permission.INTERNET" />連網權限
3.獲得消息的時候要創建文本輸入流,結束時一定要關閉輸入流。
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
暫時就這些吧。