IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> java代码发送http请求 -> 正文阅读

[网络协议]java代码发送http请求

使用springboot进行编写

导入依赖

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

?例:

? 注入bean对象

?@Autowired
? ? private RestTemplate restTemplate;
? ?
? ?执行代码,复制粘贴到方法中即可使用
? ?String url ="http://47.101.128.4:9999/login";
? ? ? ? HttpHeaders headers = new HttpHeaders();
? ? ? ? MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
? ? ? ? headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
? ? ? ? map.add("username","1009717010");
? ? ? ? map.add("pwd","1009717010");
? ? ? ? HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(map, headers);
? ? ? ? ResponseEntity<String> 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);


? ? /**
? ? ?* 封装POST请求(Map入参)
? ? ?*
? ? ?* @param url 请求的路径
? ? ?* @param map 请求的参数
? ? ?* @return
? ? ?* @throws IOException
? ? ?*/
? ? 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<NameValuePair> list = new ArrayList<>();
? ? ? ? Set<Map.Entry> 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;
? ? }

? ? /**
? ? ?* 封装POST请求(String入参)
? ? ?*
? ? ?* @param url ?请求的路径
? ? ?* @param data String类型数据
? ? ?* @return
? ? ?* @throws IOException
? ? ?*/
? ? 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;
? ? }

? ? /**
? ? ?* 封装GET请求
? ? ?*
? ? ?* @param url
? ? ?* @return
? ? ?* @throws IOException
? ? ?*/
? ? 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;
? ? }
}

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-26 09:12:22  更:2021-11-26 09:14:45 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/5 14:47:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码