Java编程中HttpURLConnection的使用

1.Java编程中,可以使用HttpURLConnection类,来访问HTTP协议的网络资源,具体使用方法,见下面实例:
public static String getPageCode(String httpUrl){
        StringBuffer htmlCode = new StringBuffer();
        try {
            InputStream in;
            URL url = new java.net.URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //数据编码格式,这里utf-8
            connection.setRequestProperty("Charset", "utf-8");
            //设置使用标准编码格式编码参数的名-值对
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 设置是否向HttpURLConnection输出
            connection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            connection.setDoInput(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置是否使用缓存
            connection.setUseCaches(true);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置超时时间
            connection.setConnectTimeout(5000);
            // 连接
            connection.connect();
            // 得到响应状态码的返回值 responseCode
            int code = connection.getResponseCode();
            if(code == HttpURLConnection.HTTP_OK){
                in = connection.getInputStream();
                java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in ,
                        "utf-8"));
                String currentLine;
                while((currentLine=breader.readLine())!=null){
                    htmlCode.append(currentLine);
                }
                //关闭流
                breader.close();
            }else {
                System.out.println("接口连接失败");
            }
            //断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            return htmlCode.toString();
        }
    }

2.注意事项。

  • HttpURLConnection对象不能直接构造,需要通过URL类中的openConnection方法类获得。
  • HttpURLConnection的connect()方法,实际上只是建立了一个与服务器的TCP连接,并没有实际发送HTTP请求,直到获取服务器响应数据(如调用getInputStream()等方法)时,才正式发送出去。
  • HttpURLConnection对象的参数配置,都需要在connect()方法执行前完成。
  • HttpURLConnection是基于HTTP协议的,其底层是通脱socket通信实现的,如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死,而不能继续往下执行。

猜你喜欢

转载自blog.csdn.net/rhx_1989/article/details/80970433