| | |
| | | package com.ltkj.web.wxUtils; |
| | | |
| | | |
| | | import cn.hutool.json.JSONUtil; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.apache.http.HttpEntity; |
| | | import org.apache.http.HttpResponse; |
| | | import org.apache.http.NameValuePair; |
| | |
| | | import java.io.*; |
| | | import java.net.HttpURLConnection; |
| | | import java.net.URL; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | |
| | | * @create 2019-02-10 下午 2:49 |
| | | */ |
| | | @Component |
| | | @Slf4j |
| | | public class HttpClientUtils { |
| | | |
| | | /** |
| | |
| | | URL url = new URL(httpUrl); |
| | | // 2. 创建 HttpURLConnection 对象 |
| | | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| | | |
| | | // 3. 设置请求方法为 POST |
| | | connection.setRequestMethod("POST"); |
| | | |
| | | // 4. 设置 Content-Type 头部字段 |
| | | connection.setRequestProperty("Content-Type", "application/json"); |
| | | |
| | | // 5. 设置其他请求头部字段(可选) |
| | | // connection.setRequestProperty("Authorization", "Bearer token"); |
| | | // connection.setRequestProperty("User-Agent", "Mozilla/5.0"); |
| | | |
| | | connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); |
| | | // 6. 向服务器发送数据 |
| | | String requestBody = maps.toString(); |
| | | String requestBody = JSONUtil.toJsonStr(maps); |
| | | log.info(httpUrl+"入参: "+requestBody); |
| | | // String requestBody1 = maps.toString(); |
| | | byte[] postData = requestBody.getBytes("UTF-8"); |
| | | connection.setDoOutput(true); |
| | | try (OutputStream outputStream = connection.getOutputStream()) { |
| | | outputStream.write(postData); |
| | | } |
| | | |
| | | // 7. 获取响应码 |
| | | int responseCode = connection.getResponseCode(); |
| | | |
| | | // 8. 获取响应数据 |
| | | try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { |
| | | try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { |
| | | String line; |
| | | StringBuilder response = new StringBuilder(); |
| | | while ((line = reader.readLine()) != null) { |
| | | response.append(line); |
| | | } |
| | | System.out.println(response.toString()); |
| | | log.info("====================================================="); |
| | | log.info(httpUrl+"出参"); |
| | | log.info(response.toString()); |
| | | connection.disconnect(); |
| | | return response.toString(); |
| | | } |