JAVA发送HTTP请求的多种方式详细总结

目录
  • 1. HttpURLConnection
  • 2. HttpClient
  • 3. CloseableHttpClient
  • 4. okhttp
  • 5. Socket
  • 6. RestTemplate
  • 总结

程序员日常工作中,发送http请求特别常见。本文以Java为例,总结发送http请求的多种方式。

1. HttpURLConnection

使用JDK原生提供的net,无需其他jar包,代码如下:

import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpTest1 {

    public static void main(String[] args) {
        HttpURLConnection con = null;

        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        try {
            URL url = new URL("http://10.30.10.151:8012/gateway.do");
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod("POST");
            //设置Content-Type,此处根据实际情况确定
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            OutputStream os = con.getOutputStream();
            Map paraMap = new HashMap();
            paraMap.put("type", "wx");
            paraMap.put("mchid", "10101");
            //组装入参
            os.write(("consumerAppId=test&serviceName=queryMerchantService&params=" + JSON.toJSONString(paraMap)).getBytes());
            //得到响应码
            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);
                }
                System.out.println("result:" + resultBuffer.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. HttpClient

需要用到commons-httpclient-3.1.jar,maven依赖如下:

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

代码如下:

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpTest2 {

    public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://10.30.10.151:8012/gateway.do");

        postMethod.addRequestHeader("accept", "*/*");
        //设置Content-Type,此处根据实际情况确定
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //必须设置下面这个Header
        //添加请求参数
        Map paraMap = new HashMap();
        paraMap.put("type", "wx");
        paraMap.put("mchid", "10101");
        postMethod.addParameter("consumerAppId", "test");
        postMethod.addParameter("serviceName", "queryMerchantService");
        postMethod.addParameter("params", JSON.toJSONString(paraMap));
        String result = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                result = postMethod.getResponseBodyAsString();
                System.out.println("result:" + result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. CloseableHttpClient

需要用到httpclient-4.5.6.jar,maven依赖如下:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

代码如下:

import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.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;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpTest3 {

    public static void main(String[] args) {
        int timeout = 120000;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        HttpPost httpPost = null;
        List<NameValuePair> nvps = null;
        CloseableHttpResponse responses = null;// 命名冲突,换一个名字,response
        HttpEntity resEntity = null;
        String result;
        try {
            httpPost = new HttpPost("http://10.30.10.151:8012/gateway.do");
            httpPost.setConfig(defaultRequestConfig);

            Map paraMap = new HashMap();
            paraMap.put("type", "wx");
            paraMap.put("mchid", "10101");
            nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("consumerAppId", "test"));
            nvps.add(new BasicNameValuePair("serviceName", "queryMerchantService"));
            nvps.add(new BasicNameValuePair("params", JSON.toJSONString(paraMap)));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

            responses = httpClient.execute(httpPost);
            resEntity = responses.getEntity();
            result = EntityUtils.toString(resEntity, Consts.UTF_8);
            EntityUtils.consume(resEntity);
            System.out.println("result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                responses.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. okhttp

需要用到okhttp-3.10.0.jar,maven依赖如下:

<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>3.10.0</version>
</dependency>

代码如下:

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpTest4 {

    public static void main(String[] args) throws IOException {
        String url = "http://10.30.10.151:8012/gateway.do";
        OkHttpClient client = new OkHttpClient();
        Map paraMap = new HashMap();
        paraMap.put("yybh", "1231231");

        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("consumerAppId", "tst")
                .addFormDataPart("serviceName", "queryCipher")
                .addFormDataPart("params", JSON.toJSONString(paraMap))
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = client
                .newCall(request)
                .execute();
        if (response.isSuccessful()) {
            System.out.println("result:" + response.body().string());
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
}

5. Socket

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

此处参考:https://www.cnblogs.com/hehongtao/p/5276425.html

代码如下:

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HttpTest6 {

    private static String encoding = "utf-8";

    public static void main(String[] args) {
        try {
            Map paraMap = new HashMap();
            paraMap.put("yybh", "12312311");
            String data = URLEncoder.encode("consumerAppId", "utf-8") + "=" + URLEncoder.encode("test", "utf-8") + "&" +
                    URLEncoder.encode("serviceName", "utf-8") + "=" + URLEncoder.encode("queryCipher", "utf-8")
                    + "&" +
                    URLEncoder.encode("params", "utf-8") + "=" + URLEncoder.encode(JSON.toJSONString(paraMap), "utf-8");
            Socket s = new Socket("10.30.10.151", 8012);
            OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append("POST /gateway.do HTTP/1.1\r\n");
            sb.append("Host: 10.30.10.151:8012\r\n");
            sb.append("Content-Length: " + data.length() + "\r\n");
            sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
            //注,这里很关键。这里一定要一个回车换行,表示消息头完,不然服务器会等待
            sb.append("\r\n");
            osw.write(sb.toString());
            osw.write(data);
            osw.write("\r\n");
            osw.flush();

            //--输出服务器传回的消息的头信息
            InputStream is = s.getInputStream();
            String line = null;
            int contentLength = 0;//服务器发送回来的消息长度
            // 读取所有服务器发送过来的请求参数头部信息
            do {
                line = readLine(is, 0);
                //如果有Content-Length消息头时取出
                if (line.startsWith("Content-Length")) {
                    contentLength = Integer.parseInt(line.split(":")[1].trim());
                }
                //打印请求部信息
                System.out.print(line);
                //如果遇到了一个单独的回车换行,则表示请求头结束
            } while (!line.equals("\r\n"));

            //--输消息的体
            System.out.print(readLine(is, contentLength));

            //关闭流
            is.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 这里我们自己模拟读取一行,因为如果使用API中的BufferedReader时,它是读取到一个回车换行后
     * 才返回,否则如果没有读取,则一直阻塞,直接服务器超时自动关闭为止,如果此时还使用BufferedReader
     * 来读时,因为读到最后一行时,最后一行后不会有回车换行符,所以就会等待。如果使用服务器发送回来的
     * 消息头里的Content-Length来截取消息体,这样就不会阻塞
     *
     * contentLe 参数 如果为0时,表示读头,读时我们还是一行一行的返回;如果不为0,表示读消息体,
     * 时我们根据消息体的长度来读完消息体后,客户端自动关闭流,这样不用先到服务器超时来关闭。
     */
    private static String readLine(InputStream is, int contentLe) throws IOException {
        ArrayList lineByteList = new ArrayList();
        byte readByte;
        int total = 0;
        if (contentLe != 0) {
            do {
                readByte = (byte) is.read();
                lineByteList.add(Byte.valueOf(readByte));
                total++;
            } while (total < contentLe);//消息体读还未读完
        } else {
            do {
                readByte = (byte) is.read();
                lineByteList.add(Byte.valueOf(readByte));
            } while (readByte != 10);
        }

        byte[] tmpByteArr = new byte[lineByteList.size()];
        for (int i = 0; i < lineByteList.size(); i++) {
            tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
        }
        lineByteList.clear();

        return new String(tmpByteArr, encoding);
    }
}

6. RestTemplate

RestTemplate 是由Spring提供的一个HTTP请求工具。比传统的Apache和HttpCLient便捷许多,能够大大提高客户端的编写效率。代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

@Autowired
RestTemplate restTemplate;

@Test
public void postTest() throws Exception {
    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
    Map paraMap = new HashMap();
    paraMap.put("type", "wx");
    paraMap.put("mchid", "10101");
    requestEntity.add("consumerAppId", "test");
    requestEntity.add("serviceName", "queryMerchant");
    requestEntity.add("params", JSON.toJSONString(paraMap));
    RestTemplate restTemplate = new RestTemplate();
    System.out.println(restTemplate.postForObject("http://10.30.10.151:8012/gateway.do",         requestEntity, String.class));
}

总结

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

(0)

相关推荐

  • 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中Https发送POST请求[亲测可用]

    1.直接建一个工具类放入即可 /** * 发送https请求共用体 */ public static JSONObject sendPost(String url,String parame,Map<String,Object> pmap) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException{ // 请求结果 JSONObject json = new JSO

  • 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.InputStreamRe

  • java发送http的get、post请求实现代码

    Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public

  • 详解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发送https请求代码实例

    1.前文:通过webService发送https请求,有两种版本,一种是携带证书验证(比较麻烦),另外一种就是直接忽略证书,本文提供的就是第二种(本人已测试过) 2.最简易代码: import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.Ma

  • java 发送http和https请求的实例

    HTTP请求: 如果需要Json格式的自己转下,度娘上N种姿势- //处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST" public static String httpRequest(String requestUrl,String requestMethod,String outputStr){ StringBuffer buffer=null; try{ URL url=new URL(requ

  • JAVA发送HTTP请求的多种方式详细总结

    目录 1. HttpURLConnection 2. HttpClient 3. CloseableHttpClient 4. okhttp 5. Socket 6. RestTemplate 总结 程序员日常工作中,发送http请求特别常见.本文以Java为例,总结发送http请求的多种方式. 1. HttpURLConnection 使用JDK原生提供的net,无需其他jar包,代码如下: import com.alibaba.fastjson.JSON; import java.io.Bu

  • 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发送HttpClient请求及接收请求结果过程的简单实例

    一. 1.写一个HttpRequestUtils工具类,包括post请求和get请求 package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.Htt

  • 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发送url请求获取返回值的二种方法

    下面提供二种方法会使用java发送url请求,并获取服务器返回的值 第一种方法: 复制代码 代码如下: import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFor

  • 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对象之间相互转化的多种方式

    第一种:使用org.apache.commons.beanutils.PropertyUtils.copyProperties()拷贝一个bean中的属性到另一个bean中,第一个参数是目标bean,第二个参数是源bean. 特点: 1.它的性能问题相当差 2.PropertyUtils有自动类型转换功能,而java.util.Date恰恰是其不支持的类型 3.PropertyUtils支持为null的场景: public static void copyProperties(Object de

随机推荐