Android 网络编程——Android 中的 HTTP 编程
2015-08-31 17:02
537 查看
Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。
区别
HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
案例
URLConnection
HTTPClient
使用 HttpClient 需要以下 6 个步骤:
步骤 1 创建 HttpClient 的实例。
步骤 2 创建某种连接方法的实例,对于 get 方法是 GetMethod,而对于 post 方法是PostMethod。
步骤 3 调用步骤 1 中创建好的实例的 execute 方法来执行步骤 2 中创建好的 method实例。
步骤 4 读 response。
步骤 5 释放连接。
步骤 6 对得到的内容进行处理。
servlet端json转化:
android端接收:
区别
HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
案例
URLConnection
String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do"; URL url; HttpURLConnection uRLConnection; public UrlConnectionToServer(){ } //向服务器发送get请求 public String doGet(String username,String password){ String getUrl = urlAddress + "?username="+username+"&password="+password; try { url = new URL(getUrl); uRLConnection = (HttpURLConnection)url.openConnection(); InputStream is = uRLConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine(); response = response + readLine; } is.close(); br.close(); uRLConnection.disconnect(); return response; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } //向服务器发送post请求 public String doPost(String username,String password){ try { url = new URL(urlAddress); uRLConnection = (HttpURLConnection)url.openConnection(); uRLConnection.setDoInput(true); uRLConnection.setDoOutput(true); uRLConnection.setRequestMethod("POST"); uRLConnection.setUseCaches(false); uRLConnection.setInstanceFollowRedirects(false); uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); uRLConnection.connect(); DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream()); String content = "username="+username+"&password="+password; out.writeBytes(content); out.flush(); out.close(); InputStream is = uRLConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine(); response = response + readLine; } is.close(); br.close(); uRLConnection.disconnect(); return response; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
HTTPClient
使用 HttpClient 需要以下 6 个步骤:
步骤 1 创建 HttpClient 的实例。
步骤 2 创建某种连接方法的实例,对于 get 方法是 GetMethod,而对于 post 方法是PostMethod。
步骤 3 调用步骤 1 中创建好的实例的 execute 方法来执行步骤 2 中创建好的 method实例。
步骤 4 读 response。
步骤 5 释放连接。
步骤 6 对得到的内容进行处理。
String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do"; public HttpClientServer(){ } public String doGet(String username,String password){ String getUrl = urlAddress + "?username="+username+"&password="+password; HttpGet httpGet = new HttpGet(getUrl); HttpParams hp = httpGet.getParams(); hp.getParameter("true"); //hp. //httpGet.setp HttpClient hc = new DefaultHttpClient(); try { HttpResponse ht = hc.execute(httpGet); if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity he = ht.getEntity(); InputStream is = he.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine(); response = response + readLine; } is.close(); br.close(); //String str = EntityUtils.toString(he); System.out.println("========="+response); return response; }else{ return "error"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return "exception"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return "exception"; } } public String doPost(String username,String password){ //String getUrl = urlAddress + "?username="+username+"&password="+password; HttpPost httpPost = new HttpPost(urlAddress); List params = new ArrayList(); NameValuePair pair1 = new BasicNameValuePair("username", username); NameValuePair pair2 = new BasicNameValuePair("password", password); params.add(pair1); params.add(pair2); HttpEntity he; try { he = new UrlEncodedFormEntity(params, "gbk"); httpPost.setEntity(he); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpClient hc = new DefaultHttpClient(); try { HttpResponse ht = hc.execute(httpPost); //连接成功 if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity het = ht.getEntity(); InputStream is = het.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine(); response = response + readLine; } is.close(); br.close(); //String str = EntityUtils.toString(he); System.out.println("=========&&"+response); return response; }else{ return "error"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return "exception"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return "exception"; } }
servlet端json转化:
resp.setContentType("text/json"); resp.setCharacterEncoding("UTF-8"); toDo = new ToDo(); List<UserBean> list = new ArrayList<UserBean>(); list = toDo.queryUsers(mySession); String body; //设定JSON JSONArray array = new JSONArray(); for(UserBean bean : list) { JSONObject obj = new JSONObject(); try { obj.put("username", bean.getUserName()); obj.put("password", bean.getPassWord()); }catch(Exception e){} array.add(obj); } pw.write(array.toString()); System.out.println(array.toString());
android端接收:
String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do"; String body = getContent(urlAddress); JSONArray array = new JSONArray(body); for(int i=0;i<array.length();i++) { obj = array.getJSONObject(i); sb.append("用户名:").append(obj.getString("username")).append("\t"); sb.append("密码:").append(obj.getString("password")).append("\n"); HashMap<String, Object> map = new HashMap<String, Object>(); try { userName = obj.getString("username"); passWord = obj.getString("password"); } catch (JSONException e) { e.printStackTrace(); } map.put("username", userName); map.put("password", passWord); listItem.add(map); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(sb!=null) { showResult.setText("用户名和密码信息:"); showResult.setTextSize(20); } else extracted(); //设置adapter SimpleAdapter simple = new SimpleAdapter(this,listItem, android.R.layout.simple_list_item_2, new String[]{"username","password"}, new int[]{android.R.id.text1,android.R.id.text2}); listResult.setAdapter(simple); listResult.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int positionId = (int) (id+1); Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show(); } }); } private void extracted() { showResult.setText("没有有效的数据!"); } //和服务器连接 private String getContent(String url)throws Exception{ StringBuilder sb = new StringBuilder(); HttpClient client =new DefaultHttpClient(); HttpParams httpParams =client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity =response.getEntity(); if(entity !=null){ BufferedReader reader = new BufferedReader(new InputStreamReader (entity.getContent(),"UTF-8"),8192); String line =null; while ((line= reader.readLine())!=null){ sb.append(line +"\n"); } reader.close(); } return sb.toString(); }
相关文章推荐
- TCP/IP、Http、Socket的区别
- windows挂载linux网络文件系统NFS
- HTTP Client使用总结
- inet_ntoa()多次调用时的问题
- java httpclient basic授权
- Android Https相关完全解析 当OkHttp遇到Https
- urllib.error.HTTPError: HTTP Error 403: Forbidden
- 【linux】centos7网络配置
- iOS-监测网络状态
- 轻松实现 网络视频播放器
- HTTP请求返回状态码详解
- xUtils中的HttpUtils全面注释
- OKHTTP封装使用
- tomcat http 文件下载
- Android 网络编程——HTTP概述
- AsyncHttpClient方式异步发送http请求
- TCP协议与流通信
- HDU1532 - Drainage Ditches 网络流之最大流
- Java利用Tomcat作为服务器与Android的Http通信
- HttpClient4.X(httpcomponents)学习笔记