码迷,mamicode.com
首页 > 移动开发 > 详细

Android http HttpURLConnection

时间:2015-09-24 13:08:39      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

 /**
  * Http get 请求
  * 
  * @param urlPath
  * 
  * 
  */
 private static String httpConnByGet(RequestUrl ru,Params params){ 
  String token = (String) params.getMap().get("token") ;
  String et = (String) params.getMap().get("et") ;
  params.getMap().remove("et");
  if(token != null ){
   params.getMap().put("token",Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));
  }
  
  String urlPath = ru.getUrl() + HttpURLConstant.QMARK + HttpURLConstant.COMMON_PARAMS + et + params.toString() ; //通用参数的设置
  Log.w("NETURL","geturl:"+urlPath);
  URL url = null;
  HttpURLConnection urlConnection = null;
  
  
  try {
   ByteArrayOutputStream outStream = new ByteArrayOutputStream();
   byte[] data = new byte[2048];    //应该不会小吧!
   int len = 0;
   url = new URL(urlPath);
      urlConnection = (HttpURLConnection) url.openConnection();  
   
//   Class<?> clazz=url.openConnection().getClass();  //看看返回什么鬼类型
//   Class<?> clazzSuper=clazz.getSuperclass();       //父类又是什么鬼啊!
      
   //getInputStream暗中执行了连接,不需要urlConnection.connect();
   urlConnection.setReadTimeout(readTimeout);                                                  // 设置请求的超时时间
   urlConnection.setConnectTimeout(connectTimeout);
   if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
    
    InputStream inStream = urlConnection.getInputStream();   //获取输入流,此时才真正建立链接
    while ((len = inStream.read(data)) != -1) {
     outStream.write(data, 0, len);
    }
    
    inStream.close();
   
    if(isDebug){Log.e(TAG,"get 返回数据"+new String(outStream.toByteArray()));}
    return new String(outStream.toByteArray());
   }else{ //返回的是HTTP的错误码,不是我们自己定义的错误码!
    
    //处理一下http的错误返回码
        
    Log.e(TAG,"get 网络连接失败"+urlConnection.getResponseCode());
    return "HTTP_ERROR-"+urlConnection.getResponseCode();
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
   Log.e(TAG,"MalformedURLException e");
  } catch (IOException e) {
   e.printStackTrace();
   Log.e(TAG,"IOException e");
  } finally{  
     
   if(urlConnection!=null){
    urlConnection.disconnect();  //总是需要关闭的吧!
   }
   
  }
  return null;  
 }   
         
 
 /**
  * Http Post 请求
  *
  * @param urlpath
  * @param paramsDatas
  */
 private static String httpConnByPost(RequestUrl ru,Params params) {
  String token = (String) params.getMap().get("token") ;
  String et = (String) params.getMap().get("et") ;
  params.getMap().remove("et");
  if(token != null ){
   params.getMap().put("token", Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));
  }  
  URL url = null;                                                       // 根据地址创建URL对象
  HttpURLConnection urlConnection = null;                               // 根据URL对象打开链接
  try {
   url = new URL(ru.getUrl());                                                          // 根据地址创建URL对象
   urlConnection = (HttpURLConnection) url.openConnection();                            // 根据URL对象打开链接
   
   urlConnection.setRequestMethod("POST");                                               // 设置请求的方式
   urlConnection.setReadTimeout(readTimeout);                                            // 设置请求的超时时间
   urlConnection.setConnectTimeout(connectTimeout);
   
   
   String paramsData = HttpURLConstant.COMMON_PARAMS + et + params.toString();           //通用参数的使用要注意
   Log.w("NETURL",url+"?"+paramsData);
   
   urlConnection.setRequestProperty("Connection", "keep-alive");                         // 设置维持长连接  
   urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 设置文件的类型
   urlConnection.setRequestProperty("Content-Length",String.valueOf(paramsData.getBytes().length)); // 设置数据的长度
   urlConnection.setRequestProperty("User-Agent","Devond_Watch,Android-device.");  // ???
   urlConnection.setDoOutput(true);   // 发送POST请求必须设置允许输出
   urlConnection.setDoInput(true);    // 发送POST请求必须设置允许输入,setDoInput的默认值就是true
   urlConnection.setUseCaches(false); // 为安全,不允许使用缓存
      
   urlConnection.connect();           //urlConnection.getInputStream()的时候会自动的打开连接的
   OutputStream os = urlConnection.getOutputStream();    //获取输出流developer
   os.write(paramsData.getBytes());
   os.flush();
   
   if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {                 
    InputStream is = urlConnection.getInputStream();          // 获取响应的输入流对象
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建字节输出流对象
    int len = 0;                                              // 定义读取的长度
    byte buffer[] = new byte[2048];                           // 定义缓冲区
    while ((len = is.read(buffer)) != -1) {                   // 按照缓冲区的大小,循环读取
     baos.write(buffer, 0, len);                           // 根据读取的长度写入到os对象中
    }
    is.close();// 释放资源   
    baos.close();
  
    final String result = new String(baos.toByteArray());
    
    if(isDebug){
     Log.e(TAG,"Post返回的数据:"+result);
    } 
    return new String(baos.toByteArray());
    
   }else{ //返回的是HTTP的错误码,不是我们自己定义的错误码!
    //处理一下http的错误返回码
    Log.e(TAG,urlConnection.getResponseCode()+"#Post 网络连接失败#"+urlConnection.getErrorStream());
    return "HTTP_ERROR-"+urlConnection.getResponseCode();
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
   Log.e(TAG,"MalformedURLException e");
  }catch (Exception e) {
   e.printStackTrace();
  }finally{
   
   if(urlConnection!=null){
    urlConnection.disconnect();
   }
   
  }
  Log.e(TAG,"Post 请求返回为空");
  return null;
 }

 

Android http HttpURLConnection

标签:

原文地址:http://my.oschina.net/zengliubao/blog/510545

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!