仅作记录
代码中包含3部分内容
1、java原生代码收发POST请求及响应
2、BufferedReader To String的两种方法
3、java 读写文件(类似copy)可用于将POST响应包写入文件
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class httpURLConnection {
public static void main(String[] args) throws Exception {
String ret = sendPost("https://www.baidu.com", "{\"key\",\"value\"}");
System.out.println(ret);
String inputFile = "source.txt";
String outputFile = "destination.txt";
readAndWriteCopy(inputFile,outputFile);
}
// java原生发送post请求
public static String sendPost(String urlStr, String jsonInputString) throws Exception {
// String urlStr = url;
// String jsonInputString = param;
URL obj = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
urlConnection.setRequestMethod("POST");
// 添加请求头
urlConnection.setRequestProperty("Content-Type", "application/json; utf-8");
urlConnection.setRequestProperty("Accept", "application/json");
// 发送POST请求必须设置如下两行
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try (OutputStream os = urlConnection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = urlConnection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
StringBuilder response = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response);
} else {
System.out.println("POST request not worked");
}
return response.toString();
}
//BufferedReader To String
public static String bufferedReaderToString(BufferedReader reader) {
// 使用Java 8的流(Stream) API简化代码
return reader.lines().collect(Collectors.joining("\n"));
// 或者使用传统的循环方式
/*StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
// 如果你想在每一行之间保留换行符,可以在这里添加
sb.append("\n");
}
return sb.toString();*/
}
// java 读取 写入文件 实现copy功能
public static void readAndWriteCopy(String inputFile, String outputFile) {
// String inputFile = "source.txt";
// String outputFile = "destination.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
// 逐行读取并写入目标文件
while ((line = reader.readLine()) != null) {
writer.write(line);
// 添加换行符以保持原文本的格式
writer.newLine();
}
System.out.println("文件内容已成功复制到新文件中。");
} catch (IOException e) {
e.printStackTrace();
System.err.println("文件读写过程中发生错误。");
}
}
}