Java程序设计(六)网络编程之HttpURLConnection的使用

大家都会发现,在工作当真,网络编程是基础的,也是很必要的,比如我们经常会用socket通信,HTTP协议,UDP协议之类的,那么今天我们将会学习到如何用HttpURLConnection这个类进行网络编程。首先我们在官网查下HttpURLConnetcion的API,官网解释如下:

A URLConnection with support for HTTP-specific features. See the spec for details.

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

The HTTP protocol handler has a few settings that can be accessed through System Properties. This covers Proxy settings as well as various other settings.

大概的意思则是

与HTTP特定功能的支持一个URLConnection。详情请参阅规范。

每个HttpURLConnection实例是用来制造单个请求,但基础网络连接到HTTP服务器可以通过其他实例可以透明共用。呼吁一个HttpURLConnection类的的InputStream和OutputStream的密切()方法的请求后,可能释放与此实例关联的网络资源,但对任何共享的持久连接没有任何影响。如果一个持久连接就是在那个时候闲置的调用disconnect()方法可以关闭基础套接字。

HTTP协议处理程序,可以通过系统属性来访问一些设置。这包括代理设置,以及其他各种设置。

而在上述叙述中,我们发现HttpURLConnection是有一个父类的URLConnetcion API文档描述如下

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:

翻译如下就是

抽象类URLConnection是代表应用程序和URL之间的通信链路的所有类的超类。这个类的实例既可以用来读取和写入由URL引用的资源。一般况下,创建一个URL连接是一个多步骤的过程

那么现在废话少说,查看例子是怎么使用的吧:

package com.baoquan.upload;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DataUpload implements Upload {

    @Override
    public boolean fileupload(String filename, String url) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean dataupload(String url, String data) {
        // TODO Auto-generated method stub

        try{
        //创建URL连接
            URL uploadurl=new URL(url);
            //打开端口通信
            HttpURLConnection con=(HttpURLConnection)uploadurl.openConnection();
            //设置相关属性设置 输入输出流打开 
            con.setDoInput(true);
            con.setDoOutput(true);
            //设置请求方式 包括POST GET
            con.setRequestMethod("POST");
            //设置请求头属性
            con.setRequestProperty("Connection","keep-Alive");
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36");
            con.setRequestProperty("Charset", "UTF-8");
                //打开输出流
            OutputStream out=new DataOutputStream(con.getOutputStream());   
            //写入数据
            out.write(data.getBytes());
            //清空缓冲区
            out.flush();
            //关闭输出流
            out.close();
            System.out.println(con.getResponseCode());
            return true;
        }
        catch(Exception e)
        {
            System.out.println("POST请求异常");
            e.printStackTrace();
        }
        return false;

    }

     public static void main(String[] args)
     {
         DataUpload dataup=new DataUpload();
         dataup.dataupload("http://localhost:8080/Server/servlet/UploadServlet", "你好世界");
     }

}

由以上代码 可以看出
1.创建URL对象
2.URL打开URL地址连接 也就是openConnection()
3.设置请求的相关方式 POST/GET
4.设置请求的头的相关属性
5.获取输入/输出流
6.读取/写入数据
7.清空缓冲区
8.关闭连接

大概就是这么的一个过程,大家都明白了吧。其实HttpURLConnection也是采用socket通信的,它内部封装了关于socket的相关信息,因此熟悉socket的通信相关编程知识的,也就能发现其实HttpURLConnection也是类似的编程步骤。好了,暂时写到这儿。有什么不对或者问题,请务必告知本人,谢谢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值