搭建简单客户端
需要处理的问题:
- 向服务器发送请求
- 包装请求体
- 将请求体数据转换为Json
- 将响应结果输出到控制台
- 解决重定向问题
- 解决错误页的输出
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
public class PostTest {
public static void main(String[] args) throws IOException {
String propsFilename = args.length >0 ? args[0] : "F:\Code\JavaLearnAll\src\main\java\Socket\post\post.properties";
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get(propsFilename))) {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
String urlString = props.remove("url").toString();
Object userAgent = props.remove("User-Agent");
Object redirects = props.remove("redirects");
cookieHandler.setDefault(new cookieManager(null, cookiePolicy.ACCEPT_ALL));
String result = doPost(new URL(urlString),props,
userAgent == null ? null : userAgent.toString(),
redirects == null ? -1 : Integer.parseInt(redirects.toString()));
System.out.println(result);
}
public static String doPost(URL url, Map