/**
* 发送Get请求
*
* @param url 请求URL
* @return {@link String}
*/
private String sendHttpRequestGet(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (IOException e) {
System.err.println("Error connecting to " + url + ": " + e.getMessage());
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 发送JSON POST请求,并返回响应结果
* @param url 请求URL
* @param json 请求的JSON数据
* @return 响应结果,如果请求失败,则返回null
*/
public static String sendHttpRequsetPost(String url, String json) {
try {
//创建一个HttpURLConnection对象
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
//设置请求方法为POST
con.setRequestMethod("POST");
//启用输出,因为我们将向服务器发送数据
con.setDoOutput(true);
//设置请求的内容类型
con.setRequestProperty("Content-Type", "application/json");
//将JSON数据写入输出流
try(OutputStream os = con.getOutputStream()) {
byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length);
}
//获取响应代码
int responseCode = con.getResponseCode();
if (responseCode != 200) {
return null; //请求失败,返回null
}
//读取响应
try(BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
return response.toString(); //返回响应结果
}
} catch(Exception e) {
System.err.println("Exception in sending POST request: " + e.getMessage());
return null;
}
}