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


操作步骤:

<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();
					}
				}
			}
		});
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值