HttpURLConnection发送GET、POST请求

/**
* GET请求
*
* @param requestUrl 请求地址
* @return
*/
public String get(String requestUrl) {

  HttpURLConnection connection = null;
  InputStream is = null;
  BufferedReader br = null;
  String result = null;

  try {
      /** 创建远程url连接对象 */
      URL url = new URL(requestUrl);

      /** 通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型 */
      connection = (HttpURLConnection) url.openConnection();

      /** 设置连接方式:GET */
      connection.setRequestMethod("GET");
      /** 设置连接主机服务器超时时间:15000毫秒 */
      connection.setConnectTimeout(15000);
      /** 设置读取远程返回的数据时间:60000毫秒 */
      connection.setReadTimeout(60000);

      /** 设置通用的请求属性 */
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      /** 发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可 */
      connection.connect();

      /*-------------------------->*/
      /** 获取所有相应头字段 */
      Map<String, List<String>> map = connection.getHeaderFields();
      /** 遍历响应头字段 */
      for (String key : map.keySet()) {
      System.out.println(key + "---------->" + map.get(key));
      }
      /* <-------------------------- */

      /** 请求成功:返回码为200 */
      if (connection.getResponseCode() == 200) {
        /** 通过connection连接,获取输入流 */
        is = connection.getInputStream();
        /** 封装输入流is,并指定字符集 */
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        /** 存放数据 */
        StringBuffer sbf = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
          sbf.append(line);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      /** 关闭资源 */
      try {

        if (null != br) {
          br.close();
        }

        if (null != is) {
          is.close();
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      /** 关闭远程连接 */
      // 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
      // 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些
      connection.disconnect();

      System.out.println("--------->>> GET request end <<<----------");
    }

    return result;
  }

/**
* POST请求
*
* @param requestUrl 请求地址
* @param param 请求数据
* @return
*/
public String post(String requestUrl, String param) {

  HttpURLConnection connection = null;
  InputStream is = null;
  OutputStream os = null;
  BufferedReader br = null;
  String result = null;

  try {
      /** 创建远程url连接对象 */
      URL url = new URL(requestUrl);

      /** 通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型 */
      connection = (HttpURLConnection) url.openConnection();

      /** 设置连接方式:POST */
      connection.setRequestMethod("POST");
      /** 设置连接主机服务器超时时间:15000毫秒 */
      connection.setConnectTimeout(15000);
      /** 设置读取远程返回的数据时间:60000毫秒 */
      connection.setReadTimeout(60000);

      /** 设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个 */
      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setDoOutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setDoInput(true);

      /** 设置通用的请求属性 */
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      /** 通过连接对象获取一个输出流 */
      os = connection.getOutputStream();
      /** 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 */
      // 若使用os.print(param);则需要释放缓存:os.flush();即使用字符流输出需要释放缓存,字节流则不需要
      if(param != null && param.length() > 0) {
        os.write(param.getBytes());
      }

      /** 请求成功:返回码为200 */
      if (connection.getResponseCode() == 200) {
        /** 通过连接对象获取一个输入流,向远程读取 */
        is = connection.getInputStream();
        /** 封装输入流is,并指定字符集 */
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        /** 存放数据 */
        StringBuffer sbf = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
          sbf.append(line);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      /** 关闭资源 */
      try {

        if (null != br) {
          br.close();
        }

        if (null != is) {
            is.close();
        }

        if (null != os) {
          os.close();
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      /** 关闭远程连接 */
      // 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
      // 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些
      connection.disconnect();

      System.out.println("--------->>> POST request end <<<----------");
    }

    return result;
  }

参考:https://blog.csdn.net/u012513972/article/details/79569888

HttpURLConnection发送GET、POST请求的更多相关文章

  1. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  2. HttpURLConnection发送POST请求(可包含文件)

    import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...

  3. Http学习之使用HttpURLConnection发送post和get请求(3)

    使用HttpURLConnection发送post和get请求 但我们常常会碰到这样一种情况: 通过HttpURLConnection来模拟模拟用户登录Web服务器,服务器使用cookie进行用户认证 ...

  4. Http学习之使用HttpURLConnection发送post和get请求(2)

    接上节Http学习之使用HttpURLConnection发送post和get请求 本节深入学习post请求. 上 节说道,post请求的OutputStream实际上不是网络流,而是写入内存,在ge ...

  5. HttpURLConnection发送请求

    每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConnection 的 InputStrea ...

  6. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

  7. HttpURLConnection 发送http请求帮助类

    java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...

  8. 谈谈Java利用原始HttpURLConnection发送POST数据

    这篇文章主要给大家介绍java利用原始httpUrlConnection发送post数据,设计到httpUrlConnection类的相关知识,感兴趣的朋友跟着小编一起学习吧 URLConnectio ...

  9. JAVA使用原始HttpURLConnection发送POST数据

    package com.newflypig.demo; /** * 使用jdk自带的HttpURLConnection向URL发送POST请求并输出响应结果 * 参数使用流传递,并且硬编码为字符串&q ...

随机推荐

  1. http://4526621.blog.51cto.com/4516621/1343369

    http://4526621.blog.51cto.com/4516621/1343369

  2. 获取weibo用户所有的关注列表

    1.新浪微博Python SDK笔记——获取粉丝列表或关注列表 http://www.tuicool.com/articles/VnQ3ye 2.friendships/friends关注列表 fri ...

  3. 小程序报错Do not have xx handler in current page的解决方法

    看到小程序这一大串的“Do not have bindName handler in current page: pages/card/card. Please make sure that bind ...

  4. 数据挖掘潜规则zz

    声明:本文指的是做数据挖掘这行,不是数据仓库 我干这行有几年了,见了很多人,干了很多公司,爆一爆这个行业的状况吧……让后来人有所了解,也让猎头挖人挖的有点方向,起码和candidates聊天的时候不至 ...

  5. ASP.NET Core 中的应用程序启动 Startup

      ASP.NET Core 应用使用Startup类来作为启动类.   Startup类中包含了ConfigureServices方法,Configure方法,IConfiguration,IHos ...

  6. AngularJS Backbone.js Ember.js 对比

    看到一篇关于AngularJS Backbone Ember.js的对比,建议看一看 说说个人的观点(本人学艺不精,只是个人的观点,不保证观点完全正确,请轻拍): backbone.js 短小精悍,非 ...

  7. 杭州.Net 相关大公司,希望对大家有帮助

    本人目前大四,还在实习.北京工作辞职后,打算回杭州看看.发现杭州的大公司相对北京好少啊,招.Net相关的公司就更少了... (我认为刚毕业生还是去大公司比较靠谱,一方面也是实力的体现)大学生,而且之前 ...

  8. MvvmLight框架使用入门(四)

    本篇我们着重介绍ViewModelBase,演示Set和RaisePropertyChanged方法的使用,以及就Cleanup方法释放资源展开讨论. ICleanup 接口.实现该接口的ViewMo ...

  9. js实现window.open不被拦截的解决方法汇总

    一.问题: 今天在处理页面ajax请求过程中,想实现请求后打开新页面,就想到通过 js window.open 来实现,但是最终都被浏览器拦截了. 二.分析: 在谷歌搜索有没有解决方法,有些说可以通过 ...

  10. LockBox的安装

    LockBox是一套加密解密库,下载地址:http://sourceforge.net/projects/tplockbox/ 我的安装的操作系统:win7 64位 安装步骤如下: 一,安装: 安装时 ...