Http请求工具类 HttpUtil.java
package com.example.demo.util;
import com.google.gson.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;
public class HttpUtil {
public static String post(String httpUrl, Object param) throws IOException {
String paramStr = toUrlString(param);
return post(httpUrl, param);
}
private static String post(String httpUrl, String param) throws IOException {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(2000);
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
String ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
connection.setRequestProperty("Content-Type", ContentType);
os = connection.getOutputStream();
os.write(param.getBytes());
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
public static String toUrlString(Object object) throws UnsupportedEncodingException {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(object);
JsonElement jsonElement = JsonParser.parseString(json);
JsonObject jsonObject = jsonElement.getAsJsonObject();
Set<String> keys = jsonObject.keySet();
StringBuilder sb = new StringBuilder();
for (String key : keys) {
String encode = URLEncoder.encode(jsonObject.get(key).getAsString(), "UTF-8");
sb.append(key).append("=").append(encode).append("&");
}
return sb.toString();
}
}
===========END===========