我们的应用常常要联网取得网络上的数据,然后进行解析,必须要先取到数据之后才能进行下一步的业务。
故网络请求是常用的操作,下面我介绍常用的三种方式,
- 第一是比较原始的方法,使用HttpURLConnection,
- 第二是Volley框架,
- 第三是xutils3框架。
1.HttpURLConnection方法
这是基于网络通信HTTP协议的网络请求,其它两种框架也是基于HTTP协议的。HTTP协议是一款基于短连接的协议,每次交互完毕后连接断开,而HTTP请求又分为GET和POST两种方式,GET请求比较简单,只需要在网址后面用?拼接请求的资源路径,如百度图片输入动漫关键字的地址
1
|
<a href= "http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB" rel= "external nofollow" >http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct= 201326592 &cl= 2 &lm= -1 &st= -1 &fm=index&fr=&sf= 1 &fmq=&pv=&ic= 0 &nc= 1 &z=&se= 1 &showtab= 0 &fb= 0 &width=&height=&face= 0 &istype= 2 &ie=utf -8 &word=%E5%8A%A8%E6%BC%AB</a>, |
可以看到index?后面跟了很多&连接的项目,这个&就是代表了一个个搜索的条件,而最后一个word=%E5%8A%A8%E6%BC%AB又是什么意思呢
就是输入的两个字”动漫”,这就是UTF-8编码后的字节,中文一个字符会编成三个字节,这是用16进制表示了一个字节。
从中也可以看到GET请求的一个限制,那就是不能传递中文,也不适合大数据量的数据提交。
而POST则就没这个限制,且安全性也比GET请求高,总结就是简单的网络请求用GET,比较复杂的要与服务器与交互的就用POST请求。
接下来就是发送GET请求和POST请求了。
GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//1. URL URL url = new URL( "http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB" ); //2. HttpURLConnection HttpURLConnection conn=(HttpURLConnection)url.openConnection(); //3. set(GET) conn.setRequestMethod( "GET" ); //4. getInputStream InputStream is = conn.getInputStream(); //5. 解析is,获取responseText,这里用缓冲字符流 BufferedReader reader = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null ; while ((line=reader.readLine()) != null ){ sb.append(line); } //获取响应文本 String responseText = sb.toString(); |
POST请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
//1. URL URL url = new URL( "http://image.baidu.com/search/index" ); //2. HttpURLConnection HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //3. POST conn.setRequestMethod( "POST" ); //4. Content-Type,这里是固定写法,发送内容的类型 conn.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" ); //5. output,这里要记得开启输出流,将自己要添加的参数用这个输出流写进去,传给服务端,这是socket的基本结构 conn.setDoOutput( true ); OutputStream os = conn.getOutputStream(); String param = "tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB" ; //一定要记得将自己的参数转换为字节,编码格式是utf-8 os.write(param.getBytes( "utf-8" )); os.flush(); //6. is InputStream is = conn.getInputStream(); //7. 解析is,获取responseText BufferedReader reader = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null ; while ((line=reader.readLine()) != null ){ sb.append(line); } //获取响应文本 String responseText = sb.toString(); |
2.Volley框架
GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//1. 创建RequestQueue,这是一个请求队列,相当于消息机制处理 private RequestQueue mQueue = Volley.newRequestQueue( this ); //2. StringRequest String url = "http://www.baidu.com" ; StringRequest req = new StringRequest(url, new Listener<String>() { //请求成功后回调 在主线程中执行 public void onResponse(String responseText) { //解析json 封装结果数据 Gson gson = new Gson(); //这里用的Gson解析JSON字符串 User result=gson.fromJson(responseText,RequestResult. class ); } }, new ErrorListener() { //请求出错时 执行回调 在主线程中执行 public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); //把req 添加到 请求队列中,一定要记得这一步,不然就相当于没有发送请求 mQueue.add(req); |
POST请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
private RequestQueue mQueue; //post请求要用commonRequest请求实现 String url= "www.baidu.com" ; CommonRequest request = new CommonRequest(Request.Method.POST,url, new Response.Listener<String>() { public void onResponse(String response) { try { //这里是请求成功后调用的接口,用JSON工具解析数据 JSONObject obj = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { } }){ //如果用POST请求,要添加参数,一定要重写这个方法来添加参数 @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> resultMap = new HashMap<String, String>(); //这里的添加的具体参数 resultMap.put("username",user.getName()); resultMap.put( "userAge" ,user.getAge()); resultMap.put( "userGender" ,user.getGender()); resultMap.put( "userSchool" ,user.getSchool()); return resultMap; } }; mQueue.add(request); } |
3.Xutils3框架
GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//第一步,新建一个请求参数对象 RequestParams params= new RequestParams( "www.baidu.com?inm=2" ); //直接调用x.http().get()方法,这里注意x是要用全局MyApplication中初始化后才可以使用,初始化方法为x.Ext.init(this) x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onCancelled(CancelledException arg0) { } @Override public void onError(Throwable arg0, boolean arg1) { Log.i( "hap.zhu" , "http_on_error,请求网络数据失败" ); } @Override public void onFinished() { } @Override public void onSuccess(String result) { Log.i( "hap.zhu" , "请求数据结果为:" +result); Gson gson= new Gson(); Result result=gson.fromJson(result,Result. class ); Log.i( "hap.zhu" , "加载结果为:" +result.toString()); } }); |
POST请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//方法同GET,就是这么简单,网络请求成功会回调监听器里的success接口,直接处理数据结果就行 RequestParams params= new RequestParams( "www.baidu.com" ); params.addBodyParameter( "email" , username); params.addBodyParameter( "password" , password); x.http().post(params, new CommonCallback<String>() { @Override public void onCancelled(CancelledException arg0) { } @Override public void onError(Throwable arg0, boolean arg1) { //网络错误也会提示错误 callback.Error(arg0.toString()); } @Override public void onFinished() { } @Override public void onSuccess(String result) { Gson gson= new Gson(); LoginResult loginResult=gson.fromJson(result, LoginResult. class ); |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/pigdreams/article/details/52459316