发送Get请求:
- 请求代码
//请求地址
String url = ***/***/***";
//入参组装
Map<String, String> map = new HashMap<>();
map.put("categoryId", categoryId.toString());
String data = HttpClientUtil.sendGet(url, map);
if (StringUtils.isBlank(data)) {
return null;
}
//获取对象
data = JSONObject.parseObject(data).get("data").toString();
//对象转换
List<BrandTO> BrandTOList = JSONArray.parseArray(data, ***.class);
- 请求通用方法
public static String sendGet(String url, Map<String, String> map) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append(url).append("?");
if (map != null) {
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=").append(value).append("&");
}
}
/**
* 返回成功状态码
*/
int SUCCESS_CODE = 200;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
String data = null;
try {
/**
* 创建HttpClient对象
*/
client = HttpClients.createDefault();
/**
* 创建URIBuilder
*/
URIBuilder uriBuilder = new URIBuilder(sb.toString());
/**
* 创建HttpGet
*/
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
/**
* 请求服务
*/
long startTime = System.currentTimeMillis();
response = client.execute(httpGet);
/**
* 获取响应吗
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
/**
* 获取返回对象
*/
HttpEntity entity = response.getEntity();
/**
* 通过EntityUitls获取返回内容
*/
data = EntityUtils.toString(entity, "UTF-8");
} else {
}
} catch (Exception e) {
} finally {
response.close();
client.close();
}
return data;
}
发送post 请求:
-
引入jar包
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.1</version> </dependency>
-
请求代码
Gson gson = new Gson();
Map<String, String> paramMap = new HashMap();
//入参
paramMap.put("***", "***");
Map<String,String> headers = new HashMap();
headers.put("***","***");
//发送 POST 请求
String sr= HttpRequest.sendPostAndHeard("https://www.h3yun.com/OpenApi/Invoke/",gson.toJson(paramMap), headers);
- 请求通用方法
public static String sendPostAndHeard(String url, String param, Map<String, String> header) throws Exception {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(15000);
// 设置通用的请求属性
if (header!=null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流 设置为UTF-8格式
OutputStream outputStream = conn.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
out = new PrintWriter(outputStreamWriter);
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
return result;
}