栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java代码发送http请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java代码发送http请求

使用springboot进行编写

导入依赖


            org.apache.httpcomponents
            httpclient
            4.5.6

 例:

  注入bean对象

 @Autowired
    private RestTemplate restTemplate;
   
   执行代码,复制粘贴到方法中即可使用
   String url ="http://47.101.128.4:9999/login";
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap map= new linkedMultiValueMap<>();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        map.add("username","1009717010");
        map.add("pwd","1009717010");
        HttpEntity> requestParams = new HttpEntity<>(map, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(url, requestParams, String.class);
        System.out.println(responseEntity.toString());

 注意事项

启动后可能会因为springboot的版本有问题显示找不到restTemplate的bean对象,只需要在启动类下加上:  

@Bean   //启动类需要手动导入bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

方法utils用来请求其他请求方式

 

import org.apache.http.HttpResponse;
import org.apache.http.NamevaluePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNamevaluePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

public class HttpClientUtils {
    private static final Logger logger = LogManager.getLogger(HttpClientUtils.class);


   
    public static String post(String url, Map map) throws IOException {
//        1、创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        2、创建请求方式的实例
        HttpPost httpPost = new HttpPost();
        try {
            httpPost.setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
//        3、添加请求参数(设置请求和传输超时时间)
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpPost.setConfig(requestConfig);

        ArrayList list = new ArrayList<>();
        Set entrySet = map.entrySet();
        for (Map.Entry entry : entrySet) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            list.add(new BasicNamevaluePair(key, value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(list, org.apache.http.protocol.HTTP.UTF_8));
//        4、发送Http请求
        HttpResponse response = httpClient.execute(httpPost);
//        5、获取返回的内容
        String result = null;
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);
            return null;
        }
//        6、释放资源
        httpPost.abort();
        httpClient.getConnectionManager().shutdown();
        return result;
    }

   
    public static String post(String url, String data) throws IOException {
//        1、创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例
        HttpPost httpPost = new HttpPost(url);
//        3、添加请求参数(设置请求和传输超时时间)
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
//        设置请求参数
        httpPost.setEntity(new StringEntity(data, "UTF-8"));
//        4、发送Http请求
        HttpResponse response = httpClient.execute(httpPost);
//        5、获取返回的内容
        String result = null;
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);
            return null;
        }
//        6、释放资源
        httpPost.abort();
        httpClient.getConnectionManager().shutdown();
        return result;
    }

   
    public static String get(String url) throws IOException {
//        1、创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例
        HttpGet httpGet = new HttpGet(url);
//        3、添加请求参数(设置请求和传输超时时间)
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpGet.setConfig(requestConfig);
//        4、发送Http请求
        HttpResponse response = httpClient.execute(httpGet);
//        5、获取返回的内容
        String result = null;
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);
            return null;
        }
//        6、释放资源
        httpGet.abort();
        httpClient.getConnectionManager().shutdown();
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603028.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号