JAVA发送HTTP请求的四种方式总结

源代码:http://github.com/lovewenyo/HttpDemo

1. 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; 

  /**
   * http协议
   */
  // socket = new Socket(this.host, this.port); 

  /**
   * https协议
   */
  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 {
  /**
   * http协议测试
   */
  //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);
  /**
   * https协议测试
   */
  SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);
  try {
   forHttpTest.sendGet();
  // forHttpTest.sendPost();
  } catch (IOException e) { 

   e.printStackTrace();
  }
 } 

}

总结

到此这篇关于JAVA发送HTTP请求的文章就介绍到这了,更多相关JAVA发送HTTP请求内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • java发送http请求并获取状态码的简单实例

    目前做项目中有一个需求是这样的,需要通过java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page/qizha/pros_add.jsp"); try { HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); try { uConnection.connect(); Sy

  • 详解Java发送HTTP请求

    前言 请求http的Demo是个人亲测过,目前该方式已经在线上运行着.因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用. 正文 使用须知 为了避免大家引错包我把依赖和涉及到包路径给大家 import java.net.HttpURLConnection; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.

  • Java 如何使用Feign发送HTTP请求

    在往常的 HTTP 调用中,一直都是使用的官方提供的 RestTemplate 来进行远程调用,该调用方式将组装代码冗余到正常业务代码中,不够优雅,因此在接触到 Feign 后,考虑使其作为一个 HTTP 发送基础,来进行远程调用. 下面就让我们来看一下,其是如何使用的. 引入依赖 首先,我们需要将 Feign 的基础依赖引入项目,因为我们只使用 Feign 的 remote 功能,因此,只引入基础依赖. 此外在项目中,我们还自定义了了 JSON 转换和 log 设置,因此还需要引入这些的第三方

  • Java发送http请求的示例(get与post方法请求)

    package com.jiucool.www.struts.action;  import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.File;  import java.io.FileReader;  import java.io.IOException;  import java.io.InputStreamReader;  import java.net.HttpURLConnect

  • JAVA通过HttpClient发送HTTP请求的方法示例

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能. HttpClient使用 使用需要引入jar包,maven项目引入如下: <dependency> <groupId>org.apache.htt

  • JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码

    JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:首先让我们先构建一个请求类(HttpRequester ).该类封装了 JAVA 实现简单请求的代码,如下: 复制代码 代码如下: import java.io.BufferedReader;  import java.io.IOException;  import java.io.InputStream;  import java.io.InputStreamReader;  import

  • URLConnection发送HTTP请求的方法_动力节点Java学院整理

    如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求. Java有原生的API可用于发送HTTP请求,即java.net.URL.java.net.URLConnection,这些API很好用.很常用,但不够简便: 所以,也流行有许多Java HTTP请求的framework,如,Apache的HttpClient. 目前项目主要用到Java原生的方式,所以,这里主要介绍此方式. 运用原生Java Api发送简单的Get请求.Post请求 HTTP请求粗分为

  • Java 发送http请求上传文件功能实例

    废话不多说了,直接给大家贴代码了,具体代码如下所示: package wxapi.WxHelper; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputSt

  • Java 发送http请求(get、post)的示例

    1.情景展示 java发送get请求.post请求(form表单.json数据)至另一服务器: 可设置HTTP请求头部信息,可以接收服务器返回cookie信息,可以上传文件等: 2.代码实现 所需jar包:httpcore-4.4.1.jar:httpclient-4.4.1.jar:httpmime-4.4.1.jar:epoint-utils-9.3.3.jar import java.io.File; import java.io.IOException; import java.io.I

  • java利用java.net.URLConnection发送HTTP请求的方法详解

    一.前言 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求. Java有原生的API可用于发送HTTP请求,即java.net.URL.java.net.URLConnection,这些API很好用.很常用,但不够简便: 所以,也流行有许多Java HTTP请求的framework,如,Apache的HttpClient. 目前项目主要用到Java原生的方式,所以,这里主要介绍此方式. 二.运用原生Java Api发送简单的Get请求.Post请求步骤

随机推荐