栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

搭建简易PostMan 发送Json数据后台逻辑

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

搭建简易PostMan 发送Json数据后台逻辑

搭建简单客户端

需要处理的问题:

  • 向服务器发送请求
  • 包装请求体
  • 将请求体数据转换为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 namevaluePairs, String userAgent, int redirects) throws IOException {

        
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (userAgent != null){
            connection.setRequestProperty("User-agent",userAgent);
        }

        if (redirects >0){
            
            
            connection.setInstanceFollowRedirects(false);
        }
        
        connection.setRequestProperty("Content-Type","application/json");
        
        
        connection.setRequestProperty("Content-Length","1024");
        
        connection.setDoOutput(true);
        
        
        try(PrintWriter out = new PrintWriter(connection.getOutputStream())) {
            StringBuilder request = new StringBuilder();
            request.append("{");
            for (Map.Entry 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
            ){
                
                String location = connection.getHeaderField("Location");
                if (location != null){
                    
                    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!");
        }

        
        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();
    }

}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340477.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号