使用http协议访问网络

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

整体而言还是很容易理解的,熟能生巧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值