HttpClient之main函数请求(xml的发送与接收)

原创
2020/05/27 11:22
阅读数 69

一,项目结构

二,pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.huawei</groupId>
  <artifactId>httpclient_tool</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>httpclient_tool</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>

    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis</artifactId>
      <version>1.4.01</version>
    </dependency>
  </dependencies>

三.读取配置文件 SystemProperty.class

package testHttpCms;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author jose
 * date 2020
 * desc 读取配置文件使用
 */
public class SystemProperty {

    /**
     * 配置文件所属的上下文路径
     */
   static String contextPath="src/main/java/testHttpCms/";

    /**
     * 配置文件名称
     */
    static String profilePath="httpClient.properties";

   private static Properties props= new Properties();

    /**
     * 初始化
     */
   static {
       try{props.load(new FileInputStream(contextPath+profilePath));

       }catch (FileNotFoundException e){
              e.printStackTrace();
       }catch (IOException E){
           E.printStackTrace();
       }
   }

    /**
     * 获取配置文件中的属性值
     * @param key 配置文件中的左值
     * @return 配置文件的右值
     */
   public static String getProperty(String key){
      return props.getProperty(key);
   }
}

四,发送请求 TestService.class

package testHttpCms;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author jose
 * date 2020
 * desc 测试案例类
 */
public class TestService {
    /**
     * 读取文件内容
     * @param xmlFile 要读取的文件
     *  @return 文件内容
     *  @throws  Exception
     */
    public  static String xmlFileToStr(File xmlFile) throws Exception {
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(xmlFile);
        Element root = doc.getRootElement();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
        Element txHeader=null;
        for (Object o:root.elements()){
            Element it=(Element) o;
            if("TX_HEADER".equals(it.getName())){
                txHeader=it;
                break;
            }
        }
        if(txHeader!=null)
            for (Object o:root.elements()){
                Element it=(Element) o;
                if("SYS_EVT_TRACE_ID".equals(it.getName())){
                    it.setText(sdf.format(new Date()));
                }else if("SYS_SND_SERIAL_NO".equals(it.getName())) {
                }  else if("SYS_REQ_TIME".equals(it.getName())){
                    it.setText(sdf.format(new Date()));
                    }
            }

        System.out.println(doc.asXML());
        return doc.asXML();
    }

    /**
     * @param FileName
     * desc 发送请求 并响应报文
     */
    public static void run(String FileName) {
        URL url = null;
        PrintWriter writer = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            File file = new File("src/main/java/testHttpCms/" + FileName);
            String out = xmlFileToStr(file);
            url = new URL(SystemProperty.getProperty("demoWebUrl"));
            conn =(HttpURLConnection)url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);

            System.out.println("发送报文n"+out);
            writer= new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            writer.print(out);
            writer.flush();
            writer.close();


            // 返回结果-字节输入流转换成字符输入流,控制台输出字符
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("响应报文n"+sb);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

五.配置文件httpClient.properties 

六,get请求

package testHttpCms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

/**
 * @Author jose
 * date 2020
 */
public class GETMain {
    public static void main(String[] args) throws IOException {

        InetAddress inetAddress = InetAddress.getLocalHost();
        // 获取本地IP
        String hostName = inetAddress.getHostAddress();

        String getUrlStr = String.format("http://%s:%s/getValue", hostName, 8080);
        get(getUrlStr);
    }

    public static void get(String urlStr) throws IOException {
        URL url = new URL(urlStr);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 返回结果-字节输入流转换成字符输入流,控制台输出字符
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb);
    }

}

七.post请求

package testHttpCms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

/**
 * @Author jose
 * date 2020
 */
public class POSTMain {
    public static void main(String[] args) throws IOException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        // 获取本地IP
        String hostName = inetAddress.getHostAddress();

        String postUrlStr = String.format("http://%s:%s/insert", hostName, 8080);
        post(postUrlStr, "{"tname": "中国上海", "tid": 1}");
    }
    public static void post(String urlStr, String body) throws IOException {
        URL url = new URL(urlStr);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置Content-Type
        connection.setRequestProperty("Content-Type", "application/json");
        // 设置是否向httpUrlConnection输出,post请求设置为true,默认是false
        connection.setDoOutput(true);

        // 设置RequestBody
        PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
        printWriter.write(body);
        printWriter.flush();
        printWriter.close();

        // 返回结果-字节输入流转换成字符输入流,控制台输出字符
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb);
    }
}

八.主函数调用

package testHttpCms;

import static testHttpCms.TestService.run;

/**
 * @Author jose
 * date 2020
 */
public class Test12401001 {
    public static void main(String[] args) {
        try{
            run("A12401001.xml");
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("出现异常");
        }

    }
}

参考文档:https://www.cnblogs.com/NguyenVm/p/10213849.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部