Android 联网操作(HttpURLConnection用法)

HttpClient

DefaultHttpClient和它的兄弟AndroidHttpClient都是HttpClient具体的实现类、它们都拥有众多的API、而且实现比较稳定、bug数量也很少、但同时也由于HttpClient的API数量过多、使得我们很难在不破坏兼容性的情况下对它进行升级和扩展、所以目前Android团队在提升和优化HttpClient方面的工作态度并不积极

HttpURLConnection

HttpURLConnection是一种多用途、轻量极的HTTP客户端、使用它来进行HTTP操作可以适用于大多数的应用程序、虽然HttpURLConnection的API提供的比较简单、但是同时这也使得我们可以更加容易地去使用和扩展它

不说过时的,讲一下HttpURLConnection用法(只是返回json):
通过URL的openConnection方法类实例化一个HttpURLConnection 对象

//通过URL的openConnection方法类实例化一个HttpURLConnection 对象
  URL url = new URL("https://www.baidu.com/");   

  URLConnection rulConnection = url.openConnection();  
           // 此处的urlConnection对象实际上是根据URL的   
            // 请求协议(此处是http)生成的URLConnection类   
            // 的子类HttpURLConnection,故此处最好将其转化   
            // 为HttpURLConnection类型的对象,以便用到   
            // HttpURLConnection更多的API.如下:   

 HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;  

设置

        // 设置 HttpURLConnection的断开时间
        httpUrlConnection .setConnectTimeout(5000);
        // 设置 HttpURLConnection的请求方式
        httpUrlConnection .setRequestMethod("GET");
        // 设置 HttpURLConnection的接收的文件类型
        httpUrlConnection .setRequestProperty(
                "Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, "
                        + "application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        // 设置 HttpURLConnection的接收语音
        conn.setRequestProperty("Accept-Language", Locale.getDefault().toString());
        // 指定请求uri的源资源地址
        httpUrlConnection .setRequestProperty("Referer", downloadUrl);
        // 设置 HttpURLConnection的字符编码
        httpUrlConnection .setRequestProperty("Accept-Charset", "UTF-8");

        httpUrlConnection .setRequestProperty("Connection", "Keep-Alive");
//响应吗和返回数据
 if (http.getResponseCode() == 200) {  
                BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "utf-8"));  

                String inputLine;  
             StringBuffer sBuffer=new StringBuffer();   
                while ((inputLine = in.readLine()) != null) {  
                    sBuffer.append(inputLine);  
                }  
                in.close();  
                System.out.println(sBuffer);

用GET方法的例子

URL url = null;  
        HttpURLConnection http = null;  
        String urls = "https://www.baidu.com/";           
        try {  
            url = new URL(urls);  
            http = (HttpURLConnection) url.openConnection();  
            http.setDoInput(true);  
            http.setDoOutput(true);  
            http.setUseCaches(false);  
            http.setConnectTimeout(50000);//设置连接超时  
        //如果在建立连接之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。  
            http.setReadTimeout(50000);//设置读取超时  
        //如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。            
            http.setRequestMethod("GET");  
            // http.setRequestProperty("Content-Type","text/xml; charset=UTF-8");  
            http.setRequestProperty("Content-Type", "application/json");  
            http.connect();  
          System.out.println(http.getResponseCode());

            if (http.getResponseCode() == 200) {  
                BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "utf-8"));  

                String inputLine;  
             StringBuffer sBuffer=new StringBuffer();   
                while ((inputLine = in.readLine()) != null) {  
                    sBuffer.append(inputLine);  
                }  
                in.close();  
                System.out.println(sBuffer);

                //result = "["+result+"]";  
            }  
        } catch (Exception e) {  
            System.out.println("err");  
        } finally {  
            if (http != null) http.disconnect();  
            //if (fis != null) fis.close();  
        }  
    }

返回值

200
<html><head>    <script>        location.replace(location.href.replace("https://","http://"));  </script></head><body>  <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript></body></html>

用post方法的例子—自己找个post传参的网址代替url和参数param ,
返回josn的就能用了

URL url = null;  

        HttpURLConnection http = null;  
        //GetIsPopupState(string mobileServiceType, string mobileServiceStr, string versionNumber, int customerId,  int type) 


        String urls = "url";

        String param = "{\"mobileServiceType\":\"MobileServiceForBRXYCS\",\"mobileServiceStr\""
                + ":\"\",\"versionNumber\":\"\",\"password\":\"111\",\"accountName\":\"138\"}";
                //json格式的参数


        try {  
            url = new URL(urls);  
            http = (HttpURLConnection) url.openConnection();  
            http.setDoInput(true);  
            http.setDoOutput(true);  
            http.setUseCaches(false);  
            http.setConnectTimeout(50000);//设置连接超时  
        //如果在建立连接之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。  
            http.setReadTimeout(50000);//设置读取超时  
        //如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。            
            http.setRequestMethod("POST");  
             //http.setRequestProperty("Content-Type","text/xml; charset=UTF-8");  
            http.setRequestProperty("Content-Type", "application/json");  
            http.connect();  
//          param = "&appName=" + appName   
//                  + "&token=" + token   
//                  + "&method=" + method   
//                  + "&dataType=" + dataType   
//                  + "&dataParams=" + dataParams   
//                  + "&sign=" + sign;  
//        
            OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream(), "utf-8");  
            osw.write(param);  
            osw.flush();  
            osw.close();  
          System.out.println(http.getResponseCode());

            if (http.getResponseCode() == 200) {  
                BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "utf-8"));  

                String inputLine;  
             StringBuffer sBuffer=new StringBuffer();   
                while ((inputLine = in.readLine()) != null) {  
                    sBuffer.append(inputLine);  
                }  
                in.close();  
                System.out.println(sBuffer);

                //result = "["+result+"]";  
            }  
        } catch (Exception e) {  
            System.out.println("err");  
        } finally {  
            if (http != null) http.disconnect();  
            //if (fis != null) fis.close();  
        }  
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值