Android之使用HttpURLConnection连接网络
文章链接:
知识点:
- HttpURLConnection进行网络请求;
- 新名词记录{Java io流操作类:BufferedReader,InputStreamReader,InputStream等}
概述
做一个APP,[必须]要请求网络,这是无疑问的。现在GitHub上面开源了好多第三方的网络库,比如volley,OKhttp,retrofit等等,这些都是很好的库,给我们做了很好的封装,使我们可以不用再去写网络请求这些比较繁杂网络请求代码。
但是,想要进步,我们就需要去到根源一探究竟,只有理解了底层的原理,才能够更好的理解网络请求这一块,需要的时候我们就可以亲自上阵,写自己的一套网络框架,不用依赖别人了。
HttpURLConnection就是Google提供给我们的API,我们可以使用它来进行网络访问。当然,我们还需要有Java的io流知识才行。
看下面的例子。
首先需要获取到HttpURLConnection的实例,一般只需new 出一个URL对象,并传入目标网络的地址,然后调用一下openConnection()方法即可打开连接。
除此之外,我们还可以设置请求的方式(“GET”“POST”)方法,GET方法会将参数拼接在URL的后面,你看到一条URL后面有”?username=yaojt&age=24”,“?”之后带的就是请求的参数。
还可以设置连接超时的时间,总不能一直等着服务器响应吧。万一木有响应呢!还有读超时时间等等。
然后是我们怎么将数据取出来呢?在连接中,获取到输入流(getInputStream()),然后使用到Java的io知识,取出来就可以了。
如下所示:
//就输入一个常用的地址好了
URL URL=new URL("http://www.baidu.com");
//打开链接
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod(“GET");
connection.setConnectTimeout(30 * 1000);
connection.setReadTimeout(5000);
InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
...
//必须关闭连接
connection.disconnect()
系不系很简单?!
需要注意的一点是:网络请求,io等耗时操作必须要在子线程中操作,Android不允许在UI线程做复杂的操作,以免引起ANR。但是这不是必须的,可以使用严苛模式,强制在UI中操作。没有开启严苛模式,Android是会抛出在UI中访问网络的异常的。
下面来一个比较完整的例子:
public class MainActivity extends Activity implements OnClickListener{
public static final int SHOW_RESPONSE=0;
private Button sendRequest=null;
private TextView responseText=null;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case SHOW_RESPONSE:
String response=(String) msg.obj;
//在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest=(Button) findViewById(R.id.send_request);
responseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("MainActivity", "onClick(View v)!");
if(v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection(){
//开启子线程发起网络请求
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection=null;
try {
URL url=new URL("http://www.baidu.com");
connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(30 * 1000);
connection.setReadTimeout(5000);
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
Message message=new Message();
message.what=SHOW_RESPONSE;
//将服务器返回的结果存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
然后这里有一个用户加载网络图片,并且返回bitmap的方法,大家可以直接拿来用就OK了。
/**
*从服务器获取图片资源
*
*@paramurl服务器上图片的链接地址
*/
privateBitmapgetHttpBitmap(String url){
URL myUrl = null;
Bitmap bitmap=null;
try{
myUrl = new (url);
//新建一个HttpURLConnection连接
HttpURLConnection conn=(HttpURLConnection)myUrl.openConnection();
conn.setConnectTimeout(2000);//设置HttpURLConnection连接超时,时间为2S
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
conn.disconnect();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return bitmap;
}
}
总结
上面的例子很容易懂,这是我们理解的第一步,也是很重要的一步。反正对我来说就是一个很好的记录和启发,希望你也是。
如有任何问题,请及时与我联系,谢谢!