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

Android使用HttpURLConnection发送HTTP请求

2017-10-27 21:03 323 查看
在这里,我们就学习下官方建议的HttpURLConnection的用法。

首先要获取到HttpURLConnection的实例

我们只需要new 出一个URL 对象,并传入目标网址,然后再调用openConnection()方法。

URL url=new URL("http://www.baidu.com");
HttpURLConnection connection=(HttpURLConnection) url.openConnection();


在得到HttpURLConnection的实例后,我们可以设置HTTP请求所使用的方法,常用的方法有两种:GET和POST。GET希望从服务器那里获取数据,POST希望把数据提交给服务器里。

connection.setRequestMethod("GET");


剩下来,我们可以进行一些自由的定制,比如设置链接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头。如:

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);


之后再调用getInputStream()方法就可以获取到从服务器返回的输入流,剩下的工作就是对输入流进行读取,最后再调用disconnec()方法将这个HTTP连接关闭掉,如图所示:

InputStream in=connection.getInputStream();
connection.disconnect();


把所有的部分都介绍完毕之后,我们就用一个实例来体验下HttpURLConnection的用法。

XML布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/BT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>


活动部分:

Button sendRequest=(Button)findViewById(R.id.BT);
responseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
try{
URL url=new URL("http://www.sina.com");
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(8000);
connection.setReadTimeout(8000);

InputStream in=connection.getInputStream();

reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);

}
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();

}finally {

if (reader!=null){
try {
reader.close();
}catch (IOException e){
e.printStackTrace();
}

}
if(connection!=null){
connection.disconnect();
}
}

}
}).start();

}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});

}
});


这样我们就把HttpURLConnection发送HTTP请求的内容就写完了,不过看了OkHttp的用法之后,我们可能就不会再用HttpURLConnection了。下一篇博客我就写下OkHttp到底是怎么用的。

目前的自己还是小白一个,把郭霖老师讲的自己理解着敲一遍,如果有一起想学习安卓的同学,我们可以一起学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android