Android Http请求方法汇总
这篇文章主要实现了在Android中使用JDK的HttpURLConnection和Apache的HttpClient访问网络资源,服务端采用python+flask编写,使用Servlet太麻烦了。关于Http协议的相关知识,可以在网上查看相关资料。代码比较简单,就不详细解释了。
【一,使用JDK中HttpURLConnection访问网络资源】
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public String executeHttpGet() { 2 String result = null; 3 URL url = null; 4 HttpURLConnection connection = null; 5 InputStreamReader in = null; 6 try { 7 url = new URL("http://10.0.2.2:8888/data/get/?token=alexzhou"); 8 connection = (HttpURLConnection) url.openConnection(); 9 in = new InputStreamReader(connection.getInputStream()); 10 BufferedReader bufferedReader = new BufferedReader(in); 11 StringBuffer strBuffer = new StringBuffer(); 12 String line = null; 13 while ((line = bufferedReader.readLine()) != null) { 14 strBuffer.append(line); 15 } 16 result = strBuffer.toString(); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } finally { 20 if (connection != null) { 21 connection.disconnect(); 22 } 23 if (in != null) { 24 try { 25 in.close(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 } 30 31 } 32 return result; 33 }
注意:因为是通过android模拟器访问本地pc服务端,所以不能使用localhost和127.0.0.1,使用127.0.0.1会访问模拟器自身。Android系统为实现通信将PC的IP设置为10.0.2.2
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public String executeHttpPost() { 2 String result = null; 3 URL url = null; 4 HttpURLConnection connection = null; 5 InputStreamReader in = null; 6 try { 7 url = new URL("http://10.0.2.2:8888/data/post/"); 8 connection = (HttpURLConnection) url.openConnection(); 9 connection.setDoInput(true); 10 connection.setDoOutput(true); 11 connection.setRequestMethod("POST"); 12 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 13 connection.setRequestProperty("Charset", "utf-8"); 14 DataOutputStream dop = new DataOutputStream( 15 connection.getOutputStream()); 16 dop.writeBytes("token=alexzhou"); 17 dop.flush(); 18 dop.close(); 19 20 in = new InputStreamReader(connection.getInputStream()); 21 BufferedReader bufferedReader = new BufferedReader(in); 22 StringBuffer strBuffer = new StringBuffer(); 23 String line = null; 24 while ((line = bufferedReader.readLine()) != null) { 25 strBuffer.append(line); 26 } 27 result = strBuffer.toString(); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } finally { 31 if (connection != null) { 32 connection.disconnect(); 33 } 34 if (in != null) { 35 try { 36 in.close(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 42 } 43 return result; 44 }
如果参数中有中文的话,可以使用下面的方式进行编码解码:
1
2
|
URLEncoder.encode( "测试" , "utf-8" ) URLDecoder.decode( "测试" , "utf-8" ); |
【二,使用Apache的HttpClient访问网络资源】
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public String executeGet() { 2 String result = null; 3 BufferedReader reader = null; 4 try { 5 HttpClient client = new DefaultHttpClient(); 6 HttpGet request = new HttpGet(); 7 request.setURI(new URI( 8 "http://10.0.2.2:8888/data/get/?token=alexzhou")); 9 HttpResponse response = client.execute(request); 10 reader = new BufferedReader(new InputStreamReader(response 11 .getEntity().getContent())); 12 13 StringBuffer strBuffer = new StringBuffer(""); 14 String line = null; 15 while ((line = reader.readLine()) != null) { 16 strBuffer.append(line); 17 } 18 result = strBuffer.toString(); 19 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } finally { 23 if (reader != null) { 24 try { 25 reader.close(); 26 reader = null; 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } 31 } 32 33 return result; 34 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public String executePost() { 2 String result = null; 3 BufferedReader reader = null; 4 try { 5 HttpClient client = new DefaultHttpClient(); 6 HttpPost request = new HttpPost(); 7 request.setURI(new URI("http://10.0.2.2:8888/data/post/")); 8 List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 9 postParameters.add(new BasicNameValuePair("token", "alexzhou")); 10 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( 11 postParameters); 12 request.setEntity(formEntity); 13 14 HttpResponse response = client.execute(request); 15 reader = new BufferedReader(new InputStreamReader(response 16 .getEntity().getContent())); 17 18 StringBuffer strBuffer = new StringBuffer(""); 19 String line = null; 20 while ((line = reader.readLine()) != null) { 21 strBuffer.append(line); 22 } 23 result = strBuffer.toString(); 24 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } finally { 28 if (reader != null) { 29 try { 30 reader.close(); 31 reader = null; 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 } 36 } 37 38 return result; 39 }
【三,服务端代码实现】
上面是采用两种方式的get和post请求的代码,下面来实现服务端的代码编写,使用python+flask真的非常的简单,就一个文件,前提是你得搭建好python+flask的环境,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #coding=utf-8 2 3 import json 4 from flask import Flask,request,render_template 5 6 app = Flask(__name__) 7 8 def send_ok_json(data=None): 9 if not data: 10 data = {} 11 ok_json = {'ok':True,'reason':'','data':data} 12 return json.dumps(ok_json) 13 14 @app.route('/data/get/',methods=['GET']) 15 def data_get(): 16 token = request.args.get('token') 17 ret = '%s**%s' %(token,'get') 18 return send_ok_json(ret) 19 20 @app.route('/data/post/',methods=['POST']) 21 def data_post(): 22 token = request.form.get('token') 23 ret = '%s**%s' %(token,'post') 24 return send_ok_json(ret) 25 26 if __name__ == "__main__": 27 app.run(host="localhost",port=8888,debug=True)
版权属于: Alex Zhou的BLOG
原文地址: http://codingnow.cn/android/723.html