iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >在JAVA中发送HTTP请求的方式有哪些
  • 932
分享到

在JAVA中发送HTTP请求的方式有哪些

2023-06-06 17:06:19 932人浏览 八月长安
摘要

在JAVA中发送Http请求的方式有哪些?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Java是什么Java是一门面向对象编程语言,可以编写桌面应用程序、WEB应用程序、分布式

在JAVA中发送Http请求的方式有哪些?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Java是什么

Java是一门面向对象编程语言,可以编写桌面应用程序、WEB应用程序、分布式系统和嵌入式系统应用程序。

HttpURLConnection

使用jdk原生提供的net,无需其他jar包;

HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

package httpURLConnection;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class HttpURLConnectionHelper { public static String sendRequest(String urlParam,String requestType) {  HttpURLConnection con = null;   BufferedReader buffer = null;   StringBuffer resultBuffer = null;   try {   URL url = new URL(urlParam);    //得到连接对象   con = (HttpURLConnection) url.openConnection();    //设置请求类型   con.setRequestMethod(requestType);    //设置请求需要返回的数据类型和字符集类型   con.setRequestProperty("Content-Type", "application/JSON;charset=GBK");    //允许写出   con.setDoOutput(true);   //允许读入   con.setDoInput(true);   //不使用缓存   con.setUseCaches(false);   //得到响应码   int responseCode = con.getResponseCode();   if(responseCode == HttpURLConnection.HTTP_OK){    //得到响应流    InputStream inputStream = con.getInputStream();    //将响应流转换成字符串    resultBuffer = new StringBuffer();    String line;    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));    while ((line = buffer.readLine()) != null) {     resultBuffer.append(line);    }    return resultBuffer.toString();   }  }catch(Exception e) {   e.printStackTrace();  }  return ""; } public static void main(String[] args) {  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.PHP?ip=120.79.75.96";  System.out.println(sendRequest(url,"POST")); }}

2. URLConnection

使用JDK原生提供的net,无需其他jar包;

建议使用HttpURLConnection

package uRLConnection;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;public class URLConnectionHelper { public static String sendRequest(String urlParam) {  URLConnection con = null;   BufferedReader buffer = null;   StringBuffer resultBuffer = null;   try {    URL url = new URL(urlParam);     con = url.openConnection();    //设置请求需要返回的数据类型和字符集类型   con.setRequestProperty("Content-Type", "application/json;charset=GBK");    //允许写出   con.setDoOutput(true);   //允许读入   con.setDoInput(true);   //不使用缓存   con.setUseCaches(false);   //得到响应流   InputStream inputStream = con.getInputStream();   //将响应流转换成字符串   resultBuffer = new StringBuffer();   String line;   buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));   while ((line = buffer.readLine()) != null) {    resultBuffer.append(line);   }   return resultBuffer.toString();  }catch(Exception e) {   e.printStackTrace();  }  return ""; } public static void main(String[] args) {  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";  System.out.println(sendRequest(url)); }}

3. HttpClient

使用方便,我个人偏爱这种方式,但依赖于第三方jar包,相关Maven依赖如下:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --><dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version></dependency
package httpClient;import java.io.IOException;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;public class HttpClientHelper { public static String sendPost(String urlParam) throws HttpException, IOException {  // 创建httpClient实例对象  HttpClient httpClient = new HttpClient();  // 设置httpClient连接主机服务器超时时间:15000毫秒  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);  // 创建post请求方法实例对象  PostMethod postMethod = new PostMethod(urlParam);  // 设置post请求超时时间  postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);  postMethod.addRequestHeader("Content-Type", "application/json");  httpClient.executeMethod(postMethod);  String result = postMethod.getResponseBodyAsString();  postMethod.releaseConnection();  return result; } public static String sendGet(String urlParam) throws HttpException, IOException {  // 创建httpClient实例对象  HttpClient httpClient = new HttpClient();  // 设置httpClient连接主机服务器超时时间:15000毫秒  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);  // 创建GET请求方法实例对象  GetMethod getMethod = new GetMethod(urlParam);  // 设置post请求超时时间  getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);  getMethod.addRequestHeader("Content-Type", "application/json");  httpClient.executeMethod(getMethod);  String result = getMethod.getResponseBodyAsString();  getMethod.releaseConnection();  return result; } public static void main(String[] args) throws HttpException, IOException {  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";  System.out.println(sendPost(url));  System.out.println(sendGet(url)); }}

4. Socket

使用JDK原生提供的net,无需其他jar包;

使用起来有点麻烦。

package socket;import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.URLEncoder; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class SocketForHttpTest {  private int port;  private String host;  private Socket socket;  private BufferedReader bufferedReader;  private BufferedWriter bufferedWriter;  public SocketForHttpTest(String host,int port) throws Exception{   this.host = host;   this.port = port;      // socket = new Socket(this.host, this.port);      socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);  }  public void sendGet() throws IOException{   //String requestUrlPath = "/z69183787/article/details/17580325";   String requestUrlPath = "/";     OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());   bufferedWriter = new BufferedWriter(streamWriter);      bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");   bufferedWriter.write("Host: " + this.host + "\r\n");   bufferedWriter.write("\r\n");   bufferedWriter.flush();   BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());   bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));   String line = null;   while((line = bufferedReader.readLine())!= null){    System.out.println(line);   }   bufferedReader.close();   bufferedWriter.close();   socket.close();  }  public void sendPost() throws IOException{    String path = "/";    String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("张三", "utf-8") + "&" +       URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");    // String data = "name=zhigang_jia";    System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);       OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");    bufferedWriter = new BufferedWriter(streamWriter);        bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");    bufferedWriter.write("Host: " + this.host + "\r\n");    bufferedWriter.write("Content-Length: " + data.length() + "\r\n");    bufferedWriter.write("Content-Type: application/x-www-fORM-urlencoded\r\n");    bufferedWriter.write("\r\n");    bufferedWriter.write(data);    bufferedWriter.write("\r\n");    bufferedWriter.flush();    BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    String line = null;    while((line = bufferedReader.readLine())!= null)    {     System.out.println(line);    }    bufferedReader.close();    bufferedWriter.close();    socket.close();  }  public static void main(String[] args) throws Exception {      //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);      SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);   try {    forHttpTest.sendGet();   // forHttpTest.sendPost();   } catch (IOException e) {    e.printStackTrace();   }  } }

看完上述内容,你们掌握在JAVA中发送HTTP请求的方式有哪些的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网精选频道,感谢各位的阅读!

--结束END--

本文标题: 在JAVA中发送HTTP请求的方式有哪些

本文链接: https://www.lsjlt.com/news/248073.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 在JAVA中发送HTTP请求的方式有哪些
    在JAVA中发送HTTP请求的方式有哪些?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。Java是什么Java是一门面向对象编程语言,可以编写桌面应用程序、Web应用程序、分布式...
    99+
    2023-06-06
  • JAVA发送HTTP请求的方式有哪些
    这篇文章主要介绍“JAVA发送HTTP请求的方式有哪些”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“JAVA发送HTTP请求的方式有哪些”文章能帮助大家解决问题。1. HttpURLConnecti...
    99+
    2023-07-05
  • java发送http get请求的两种方式
    长话短说,废话不说一、第一种方式,通过HttpClient方式,代码如下:public static String httpGet(String url, String charset) throws HttpException, IO...
    99+
    2023-05-31
    java http get
  • 【Java】汇总Java中发送HTTP请求的7种方式
    今天在项目中发现一个功能模块是额外调用的外部服务,其采用CloseableHttpClient调用外部url中的接口…… public void handleHttp(String jsonParam...
    99+
    2023-10-11
    java http
  • 利用java实现发送http或get请求的方法有哪些
    这篇文章将为大家详细讲解有关利用java实现发送http或get请求的方法有哪些,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、第一种方式,通过HttpClient方式,代码如下:publ...
    99+
    2023-05-31
    java http请求 get请求
  • JAVA发送HTTP请求的多种方式详细总结
    目录1. HttpURLConnection2. HttpClient3. CloseableHttpClient4. okhttp5. Socket6. RestTemplate总...
    99+
    2023-01-30
    java发送http请求 java http请求
  • php发送get请求的方法有哪些
    PHP发送GET请求的方法有以下几种:1. 使用file_get_contents函数:可以通过该函数向指定的URL发送GET请求,...
    99+
    2023-08-11
    php
  • Node发起HTTP请求的方法有哪些
    本篇内容主要讲解“Node发起HTTP请求的方法有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Node发起HTTP请求的方法有哪些”吧!正文Node.js HTTPS ModuleNode...
    99+
    2023-07-04
  • C#通过GET/POST方式发送Http请求
    目录两者的区别:参数传输数据的大小 安全性 Get请求 Post请求 介绍http请求的两种方式,get和post方式。并用C#语言实现,如何请求url并获取返回的数据 两者的区别:...
    99+
    2024-04-02
  • HTTP请求:如何在Bash中发送它们?
    HTTP请求是在Web开发中非常常见的一个概念。它允许我们向Web服务器发送请求,并获取响应。在本文中,我们将介绍如何使用Bash发送HTTP请求。 Bash是一种Unix Shell,它提供了一种在命令行中执行操作的简单方式。这使得Ba...
    99+
    2023-08-15
    path bash http
  • java请求接口的方式有哪些
    Java请求接口的方式有以下几种:1. 使用HttpURLConnection:使用Java标准库中的HttpURLConnecti...
    99+
    2023-10-25
    java
  • Java中Https发送POST请求的方法
    这篇文章主要介绍Java中Https发送POST请求的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Java的优点是什么1. 简单,只需理解基本的概念,就可以编写适合于各种情况的应用程序;2. 面向对象;3. 分...
    99+
    2023-06-15
  • HTTP POST请求发送form-data格式的数据
    1、业务需求 发送请求给第三方服务的接口,且请求报文格式为multipart/form-data的数据。支持复杂类型的参数,包含文件类型 2、 依赖包 org.projectlomboklombokcom.alibabafastjson1....
    99+
    2023-08-19
    java servlet 开发语言
  • 实现HTTP请求的方法有哪些
    本篇文章为大家展示了实现HTTP请求的方法有哪些,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。一、HTTP的请求与响应HTTP协议(HyperText Transfer Protocol,超文本传输...
    99+
    2023-05-31
    http请求 请求
  • 图片的HTTP请求方法有哪些
    这篇文章主要介绍“图片的HTTP请求方法有哪些”,在日常操作中,相信很多人在图片的HTTP请求方法有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”图片的HTTP请求方法有哪些”的疑惑有所帮助!接下来,请跟...
    99+
    2023-06-08
  • JAVA中的HTTP请求怎么利用HttpClient实现发送
    JAVA中的HTTP请求怎么利用HttpClient实现发送?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。HttpClient介绍HttpClient 不是一个...
    99+
    2023-05-31
    java httpclient http
  • PHP使用HTTP请求发送邮件的方法
    PHP是一种广泛使用的编程语言,其中一个常见的应用就是发送电子邮件。在这篇文章中,我们将讨论如何使用HTTP请求发送邮件。我们将从以下几个方面来介绍这个主题:什么是HTTP请求发送邮件的基本原理使用PHP发送HTTP请求发送邮件的示例代码什...
    99+
    2023-05-21
    Http请求 PHP 邮件发送
  • ajax请求的方式有哪些
    这篇文章主要讲解了“ajax请求的方式有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ajax请求的方式有哪些”吧! aja...
    99+
    2024-04-02
  • ajax的请求方式有哪些
    Ajax的请求方式有以下几种:1. GET:使用GET方法发送请求,获取指定资源。这是最常用的请求方式之一。例如:`$.get(ur...
    99+
    2023-09-13
    ajax
  • 微信小程序开发中http请求有哪些
    微信小程序开发中http请求有哪些,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。在微信小程序进行网络通信,只能和指定的域名进行通信,微信小程序...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作