在Android中发送HTTP请求的方式一般有两种:1.是HttpUrlConnection,2.是HttpClient.
第一个实例 是使用HttpUrlConnection的用法实现访问网络:
界面:主界面中有一个 按钮和一个状态scrolview中的textview;
具体代码如下:
public class MainActivity extends Activity {
protected int SHOW_REPONSE = 2;
private ProgressDialog pd;
private TextView tv;
//访问网络数据需要异步加载数据(如果用xutils就不用,xutils本身是异步,但是直接拿来用就行)
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if (msg.what==SHOW_REPONSE) {
pd.dismiss();
String text = msg.obj.toString();
tv.setText(text);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.response_text);
pd = new ProgressDialog(this);
pd.setProgress(ProgressDialog.STYLE_SPINNER);
}
public void send_request(View v)
{
pd.show();
sendRequestWithHttpURLConnection();
}
private void sendRequestWithHttpURLConnection() {
// TODO Auto-generated method stub
//开启线程来发起网络请求
new Thread(){
public void run() {
HttpURLConnection connection =null;//声明
try {
URL url = new URL("http://www.zhihu.com");//new一个url对象
try {
connection = (HttpURLConnection) url.openConnection();//获取connection实例
connection.setRequestMethod("GET");//设置是 get 或者是post
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();//得到connection从服务器得到的输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine())!=null) {
builder.append(line);
}
Message msg = new Message();
msg.what = SHOW_REPONSE;
msg.obj = builder.toString();
handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
第二个实例: 用HttpClient访问网络
具体代码:
private void sendRequestWithHttpURLConnection() {
// TODO Auto-generated method stub
//开启线程来发起网络请求
new Thread(){
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.zhihu.com/");
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String responseresult = EntityUtils.toString(entity,"uft-8");
Message msg = new Message();
msg.what = SHOW_REPONSE;
msg.obj = responseresult.toString();
handler.sendMessage(msg);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
整体而言还是很容易理解的,熟能生巧!