您的位置:首页 > 理论基础 > 计算机网络

URLConnection 和HttpURLConnection

2016-07-14 10:42 691 查看
转载自:http://blog.csdn.net/caesardadi/article/details/8622266

         URLConnection和HttpURLConnection使用的都是Java.net中的类,属于标准的java接口。

        HttpURLConnection继承自URLConnection,差别在与HttpURLConnection仅仅针对Http连接。

         基本步骤:

         1) 创建 URL 以及 URLConnection / HttpURLConnection 对象

         2) 设置连接参数

         3) 连接到服务器

         4) 向服务器写数据

         5)从服务器读取数据

[java] view
plain copy

  public void urlConnection()  

   {  

       String urltext = "";  

       try {  

//        方法一:  

          URL url = new URL(urltext);  

          URLConnection conn = url.openConnection();//取得一个新的链接对指定的URL  

          conn.connect();//本方法不会自动重连  

          InputStream is = conn.getInputStream();  

          is.close();//关闭InputStream  

//        方法二:  

          URL url2 = new URL(urltext);  

          InputStream is2 = url2.openStream();  

          is2.close();//关闭InputStream  

          //URL对象也提供取得InputStream的方法。URL.openStream()会打开自动链接,所以不需要运行openConnection  

  

          //方法三:本方法同一,但是openConnection返回值直接转为HttpsURLConnection,  

          //这样可以使用一些Http连接特有的方法,如setRequestMethod  

          URL url3 = new URL(urltext);  

          HttpsURLConnection conn3 =(HttpsURLConnection)url.openConnection();  

          conn3.setRequestMethod("POST");  

          //允许Input、Output,不使用Cache  

          conn3.setDoInput(true);  

          conn3.setDoOutput(true);  

          conn3.setUseCaches(false);  

          /* 

           * setRequestProperty 

           */  

          conn3.setRequestProperty("Connection", "Keep-Alive");  

          conn3.setRequestProperty("Charset", "UTF-8");  

          conn3.setRequestProperty("Content-type", "multipart/form-data;boundary=*****");  

          //在与服务器连接之前,设置一些网络参数  

          conn3.setConnectTimeout(10000);  

            

          conn3.connect();  

        // 与服务器交互:向服务器端写数据,这里可以上传文件等多个操作  

          OutputStream outStream = conn3.getOutputStream();  

          ObjectOutputStream objOutput = new ObjectOutputStream(outStream);  

          objOutput.writeObject(new String("this is a string…"));  

          objOutput.flush();  

      

          // 处理数据, 取得响应内容  

          InputStream is3 = conn.getInputStream();  

          is3.close();//关闭InputStream  

       } catch (IOException e) {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

        }  

   }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: