广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JAVA发送HTTP请求的多种方式详细总结
  • 525
分享到

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

java发送http请求java http请求 2023-01-30 18:01:27 525人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录1. HttpURLConnection2. HttpClient3. CloseableHttpClient4. okhttp5. Socket6. 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", "*
    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请求方式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: JAVA发送HTTP请求的多种方式详细总结

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

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

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

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

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作