搭建简单客户端
需要处理的问题:
- 向服务器发送请求
- 包装请求体
- 将请求体数据转换为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;
/**
* @BelongsProject: JavaLearnAll
* @BelongsPackage: Socket.post
* @Author: Wang Haipeng
* @CreateTime: 2021-10-21 08:47
* @Description: 编写客户端与服务器交互,向服务器发送请求并输出
*/
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();
}
/*访问的URL*/
String urlString = props.remove("url").toString();
/*用户端浏览器类型*/
Object userAgent = props.remove("User-Agent");
/*重定向次数*/
Object redirects = props.remove("redirects");
/*设置全局的Cookie 处理器*/
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);
}
/**
*
* @param url 用于请求服务器的URL
* @param nameValuePairs 连接/请求信息
* @param userAgent 用户客户端类型
* @param redirects 响应次数
* @return 打印服务器的请求
* @Description: 向服务器发送请求,如果有重定向则处理重定向,如果没有重定就将服务器的的响应数据打印到控制台上
*
*/
public static String doPost(URL url, Map<Object,Object> nameValuePairs, String userAgent, int redirects) throws IOException {
/*所有满足URL类的协议都可以通过URLConnection 来封装请求或者响应的对象*/
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (userAgent != null){
connection.setRequestProperty("User-agent",userAgent);
}
if (redirects >0){
/*HttpURLConnection.setFollowRedirects 设置所有的http 连接自动处理重定向*/
/*设置本次连接自动处理重定向*/
connection.setInstanceFollowRedirects(false);
}
/*设置请求头的属性*/
connection.setRequestProperty("Content-Type","application/json");
/*HTTP协议要求必须发送下请求的的长度*/
/*
这一段设置请求长度的代码必须放到PrintiWriter 建立之前,因为PrintWriter 对象建立就一定会建立连接
而请求头必须在PrintWrter 前发送给服务器
*/
connection.setRequestProperty("Content-Length","1024");
/*开启响应输出*/
connection.setDoOutput(true);
/*将数据简单封装为Json 数据传递给服务器*/
try(PrintWriter out = new PrintWriter(connection.getOutputStream())) {
StringBuilder request = new StringBuilder();
request.append("{");
for (Map.Entry<Object,Object> pair : nameValuePairs.entrySet()){
String name = pair.getKey().toString();
String value = pair.getValue().toString();
String result = '\"'+name+'\"'+':'+'\"'+value+'\"'+',';
request.append(result);
}
request.append("}");
request.deleteCharAt(request.length()-2);
System.out.println(request.toString());
out.print(request.toString());
}
String encoding = connection.getContentEncoding();
if (encoding == null){
encoding = "UTF-8";
}
/*
* 处理无法进行自动重定向的情况
* */
if (redirects > 0){
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER
){
/*重定向的目标位置会放置在响应头的Location 字段*/
String location = connection.getHeaderField("Location");
if (location != null){
/*返回当前的Connection 建立连接的URL对象*/
URL base = connection.getURL();
/*断开连接*/
connection.disconnect();
return doPost(new URL(base,location), nameValuePairs, userAgent, redirects-1);
}
}
}else if (redirects == 0){
throw new IOException("Too many redirects!");
}
/**
* 处理从服务器读数据过程中服务器端出错的情况
* 当读取响应过程中服务器端出现错误,那么在调用connection.getInputStream()
* 时会抛出一个错误页面,为了捕获这个错误页,可以通过getErrorStream方法:
*/
StringBuilder response = new StringBuilder();
try(Scanner in = new Scanner(connection.getInputStream(),encoding)) {
while (in.hasNextLine()){
response.append(in.nextLine());
response.append("\n");
}
}catch(IOException e){
InputStream err = connection.getInputStream();
/*如果服务器不存在错误的响应页,那么就抛出这个错误客户端不去处理,一般会有响应页*/
if (err == null){
throw e;
}
try(Scanner in = new Scanner(err)) {
response.append(in.nextLine());
response.append("\n");
}
}
return response.toString();
}
}
|