您的位置:首页 > 理论基础 > 计算机网络

http操作访问网络

2013-01-12 19:35 399 查看
操作步骤:

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

}

}

}

});

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: