关闭

Android进阶2之Http操作访问网络

2494人阅读 评论(0) 收藏 举报


操作步骤:

<1>

生成请求对象

HttpGet httpGet = new HttpGet("请求地址。。。。。");

<2>

生成客户端对象

HttpClient httpClient = new DefaultHttpClient();

<3>

执行请求

HttpResponse httpResponse = httpClient.execute(httpGet);

<4>

接受响应

HttpEntity  httpEntity = httpResponse.getEntity();

<5>得到数据流

InputStream  inputStream = httpEntity.getContent();

注意:

要添加权限: <uses-permission android:name="android.permission.INTERNET" />

具体实现:

package xiaosi.httpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpResponseActivity extends Activity
{
	private Button			button			= null;
	private TextView		text			= null;
	private HttpResponse	httpResponse	= null;
	private HttpEntity		httpEntity		= null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		text = (TextView) findViewById(R.id.text);
		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v)
			{
				// 生成一个请求对象,参数就是地址
				HttpGet httpGet = new HttpGet("http://www.baidu.com");
				// 生成Http客户端
				HttpClient httpClient = new DefaultHttpClient();
				InputStream inputStream = null;
				// 使用HTTP客户端发送请求对象
				try
				{
					// 发送请求的响应
					httpResponse = httpClient.execute(httpGet);
					// 代表接收的http消息,服务器返回的消息都在httpEntity
					httpEntity = httpResponse.getEntity();
					if(httpResponse.getStatusLine().getStatusCode() == 200){
						inputStream = httpEntity.getContent();
						BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
						String result = "";
						String line = "";
						while ((line = reader.readLine()) != null)
						{
							result = result + line;
						}
						
						text.setText(result);
					}
				}
				catch (ClientProtocolException e)
				{
					e.printStackTrace();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					try
					{
						inputStream.close();
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		});
	}
}


2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2672786次
    • 积分:28990
    • 等级:
    • 排名:第185名
    • 原创:495篇
    • 转载:224篇
    • 译文:0篇
    • 评论:572条
    博客专栏
    最新评论