package com.yc.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClients;
import org.apache.http.params.HttpParams;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author 杨超
* @Package com.yc.util
* @Date 2022/11/24 15:34
*/
public class HttpUtil {
public static void main(String[] args) {
// 发送 GET 请求
// String s=HttpUtil.sendGet("http://www.baidu.com", "");
// Map<String, Object> s = HttpUtil.sendGet("http://127.0.0.1:6868/yc/test", "");
// System.out.println(s);
//
//
// post 请求方式
// JSONObject paramJson = new JSONObject();
// paramJson.put("appid", "yc");
// paramJson.put("appkey", "yc");
// paramJson.put("paramval1", "110");
// Map<String,Object> paramMap=(Map<String, Object>)paramJson;
String result = HttpUtil.sendPostByJson(paramJson, "http://www.baidu.com");
// Map<String,Object> map = HttpUtil.sendPostByJson(paramMap, "http://127.0.0.1:6868/yc/tests");
JSONObject jsonObject = JSONObject.parseObject(result);
// System.out.println("data::" + map);
//
// http:
//127.0.0.1:6868/yc/wechat/login
//
// Map<String,Object> map =new HashMap<>();
//
// Map<String, Object> map = HttpUtil.sendPostByJson(paramMap, " http://127.0.0.1:6868/yc/wechat/login");
JSONObject jsonObject = JSONObject.parseObject(result);
// System.out.println("data::" + map);
/**
* wechat:
* AppID: xxxx
* AppSecret: xxxxx
* url: https://api.weixin.qq.com
*/
// https://api.weixin.qq.com/cgi-bin/token
Map<String, Object> s = HttpUtil.sendGet("https://api.weixin.qq.com",
"xxxxx");
System.out.println(s);
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static Map<String, Object> sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
JSONObject jsons = JSONObject.parseObject(result);
Map<String, Object> mapResult = (Map<String, Object>) jsons;
return mapResult;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param map 请求参数,请求参数应该是 json 的形式。
* @return 所代表远程资源的响应结果
*/
public static Map<String, Object> sendPostByJson(Map<String, Object> map, String url) {
JSONObject json = new JSONObject(map);
String result = "";
HttpPost post = new HttpPost(url);
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity postingString = new StringEntity(json.toString(), "utf-8");
post.setEntity(postingString);
HttpResponse response = (HttpResponse) httpClient.execute(post);
InputStream in = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
strber.append(line + '\n');
}
br.close();
in.close();
result = strber.toString();
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
result = "服务器异常";
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
} finally {
post.abort();
}
JSONObject jsons = JSONObject.parseObject(result);
Map<String, Object> mapResult = (Map<String, Object>) jsons;
return mapResult;
}
public static Map<String, Object> sendPostByPhone(Map<String, Object> map, String url,String accessToken) {
JSONObject json = new JSONObject(map);
String result = "";
HttpPost post = new HttpPost(url);
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity postingString = new StringEntity(json.toString(), "utf-8");
post.setEntity(postingString);
HttpResponse response = (HttpResponse) httpClient.execute(post);
InputStream in = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
strber.append(line + '\n');
}
br.close();
in.close();
result = strber.toString();
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
result = "服务器异常";
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
} finally {
post.abort();
}
JSONObject jsons = JSONObject.parseObject(result);
Map<String, Object> mapResult = (Map<String, Object>) jsons;
return mapResult;
}
}
Java请求第三方接口HttpUtil
于 2023-03-10 17:50:41 首次发布