热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

详解java实现HTTP请求的三种方式

目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP

目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

自己在工作中三种方式都用到过,总结一下分享给大家,也方便自己以后使用,话不多说上代码。

第一种方式:java原生HttpURLConnection

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
  public static String doGet(String httpurl) {
    HttpURLConnection cOnnection= null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;// 返回结果字符串
    try {
      // 创建远程url连接对象
      URL url = new URL(httpurl);
      // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
      cOnnection= (HttpURLConnection) url.openConnection();
      // 设置连接方式:get
      connection.setRequestMethod("GET");
      // 设置连接主机服务器的超时时间:15000毫秒
      connection.setConnectTimeout(15000);
      // 设置读取远程返回的数据时间:60000毫秒
      connection.setReadTimeout(60000);
      // 发送请求
      connection.connect();
      // 通过connection连接,获取输入流
      if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        // 封装输入流is,并指定字符集
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        // 存放数据
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      connection.disconnect();// 关闭远程连接
    }

    return result;
  }

  public static String doPost(String httpUrl, String param) {

    HttpURLConnection cOnnection= null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      // 通过远程url连接对象打开连接
      cOnnection= (HttpURLConnection) url.openConnection();
      // 设置连接请求方式
      connection.setRequestMethod("POST");
      // 设置连接主机服务器超时时间:15000毫秒
      connection.setConnectTimeout(15000);
      // 设置读取主机服务器返回数据超时时间:60000毫秒
      connection.setReadTimeout(60000);

      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setDoOutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setDoInput(true);
      // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 通过连接对象获取一个输出流
      os = connection.getOutputStream();
      // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
      os.write(param.getBytes());
      // 通过连接对象获取一个输入流,向远程读取
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        // 对输入流对象进行包装:charset根据工作项目组的要求来设置
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循环遍历一行一行读取数据
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 断开与远程地址url的连接
      connection.disconnect();
    }
    return result;
  }
}

第二种方式:apache HttpClient3.1

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

  public static String doGet(String url) {
    // 输入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 创建httpClient实例
    HttpClient httpClient = new HttpClient();
    // 设置http连接主机服务超时时间:15000毫秒
    // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建一个Get方法实例对象
    GetMethod getMethod = new GetMethod(url);
    // 设置get请求超时为60000毫秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
    try {
      // 执行Get方法
      int statusCode = httpClient.executeMethod(getMethod);
      // 判断返回码
      if (statusCode != HttpStatus.SC_OK) {
        // 如果状态码返回的不是ok,说明失败了,打印错误信息
        System.err.println("Method faild: " + getMethod.getStatusLine());
      } else {
        // 通过getMethod实例,获取远程的一个输入流
        is = getMethod.getResponseBodyAsStream();
        // 包装输入流
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        // 读取封装的输入流
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp).append("\r\n");
        }

        result = sbf.toString();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 释放连接
      getMethod.releaseConnection();
    }
    return result;
  }

  public static String doPost(String url, Map paramMap) {
    // 获取输入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(url);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

    NameValuePair[] nvp = null;
    // 判断参数map集合paramMap是否为空
    if (null != paramMap && paramMap.size() > 0) {// 不为空
      // 创建键值参数对象数组,大小为参数的个数
      nvp = new NameValuePair[paramMap.size()];
      // 循环遍历参数集合map
      Set> entrySet = paramMap.entrySet();
      // 获取迭代器
      Iterator> iterator = entrySet.iterator();

      int index = 0;
      while (iterator.hasNext()) {
        Entry mapEntry = iterator.next();
        // 从mapEntry中获取key和value创建键值对象存放到数组中
        try {
          nvp[index] = new NameValuePair(mapEntry.getKey(),
              new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        index++;
      }
    }
    // 判断nvp数组是否为空
    if (null != nvp && nvp.length > 0) {
      // 将参数存放到requestBody对象中
      postMethod.setRequestBody(nvp);
    }
    // 执行POST方法
    try {
      int statusCode = httpClient.executeMethod(postMethod);
      // 判断是否成功
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method faild: " + postMethod.getStatusLine());
      }
      // 获取远程返回的数据
      is = postMethod.getResponseBodyAsStream();
      // 封装输入流
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      StringBuffer sbf = new StringBuffer();
      String temp = null;
      while ((temp = br.readLine()) != null) {
        sbf.append(temp).append("\r\n");
      }

      result = sbf.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 释放连接
      postMethod.releaseConnection();
    }
    return result;
  }
}

第三种方式:apache  httpClient4.5

package com.powerX.httpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient4 {

  public static String doGet(String url) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse respOnse= null;
    String result = "";
    try {
      // 通过址默认配置创建一个httpClient实例
      httpClient = HttpClients.createDefault();
      // 创建httpGet远程连接实例
      HttpGet httpGet = new HttpGet(url);
      // 设置请求头信息,鉴权
      httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 设置配置请求参数
      RequestConfig requestCOnfig= RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
          .setConnectionRequestTimeout(35000)// 请求超时时间
          .setSocketTimeout(60000)// 数据读取超时时间
          .build();
      // 为httpGet实例设置配置
      httpGet.setConfig(requestConfig);
      // 执行get请求得到返回对象
      respOnse= httpClient.execute(httpGet);
      // 通过返回对象获取返回数据
      HttpEntity entity = response.getEntity();
      // 通过EntityUtils中的toString方法将结果转换为字符串
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != response) {
        try {
          response.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }

  public static String doPost(String url, Map paramMap) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpRespOnse= null;
    String result = "";
    // 创建httpClient实例
    httpClient = HttpClients.createDefault();
    // 创建httpPost远程连接实例
    HttpPost httpPost = new HttpPost(url);
    // 配置请求参数实例
    RequestConfig requestCOnfig= RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
        .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
        .setSocketTimeout(60000)// 设置读取数据连接超时时间
        .build();
    // 为httpPost实例设置配置
    httpPost.setConfig(requestConfig);
    // 设置请求头
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    // 封装post请求参数
    if (null != paramMap && paramMap.size() > 0) {
      List nvps = new ArrayList();
      // 通过map集成entrySet方法获取entity
      Set> entrySet = paramMap.entrySet();
      // 循环遍历,获取迭代器
      Iterator> iterator = entrySet.iterator();
      while (iterator.hasNext()) {
        Entry mapEntry = iterator.next();
        nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
      }

      // 为httpPost设置封装好的请求参数
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    try {
      // httpClient对象执行post请求,并返回响应参数对象
      httpRespOnse= httpClient.execute(httpPost);
      // 从响应对象中获取响应内容
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != httpResponse) {
        try {
          httpResponse.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }
}

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。

以上所述是小编给大家介绍的java实现HTTP请求的三种方式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 如何用UE4制作2D游戏文档——计算篇
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了如何用UE4制作2D游戏文档——计算篇相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • 关于我们EMQ是一家全球领先的开源物联网基础设施软件供应商,服务新产业周期的IoT&5G、边缘计算与云计算市场,交付全球领先的开源物联网消息服务器和流处理数据 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • 使用正则表达式爬取36Kr网站首页新闻的操作步骤和代码示例
    本文介绍了使用正则表达式来爬取36Kr网站首页所有新闻的操作步骤和代码示例。通过访问网站、查找关键词、编写代码等步骤,可以获取到网站首页的新闻数据。代码示例使用Python编写,并使用正则表达式来提取所需的数据。详细的操作步骤和代码示例可以参考本文内容。 ... [详细]
  • uniapp开发H5解决跨域问题的两种代理方法
    本文介绍了uniapp开发H5解决跨域问题的两种代理方法,分别是在manifest.json文件和vue.config.js文件中设置代理。通过设置代理根域名和配置路径别名,可以实现H5页面的跨域访问。同时还介绍了如何开启内网穿透,让外网的人可以访问到本地调试的H5页面。 ... [详细]
author-avatar
失憶壹瞬間_533
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有