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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:18   1531   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(); } } } }); } }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP