main.xml
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.Nameva luePair;
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.BasicNameva luePair;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.Nameva lueTable;
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(