URLConnection 和HttpURLConnection

8 篇文章 0 订阅
6 篇文章 0 订阅

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

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


         基本步骤:
         1) 创建 URL 以及 URLConnection / HttpURLConnection 对象
         2) 设置连接参数
         3) 连接到服务器
         4) 向服务器写数据
         5)从服务器读取数据

  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();
		}
   }


  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值