JavaFx,Java桌面程序初体验

2020-06-02  本文已影响0人  Ktry

为了方便的做接口测试,无聊做了个接口测试的工具,下面是一些截图

QQ截图20200602123330.png QQ截图20200602123522.png

代码实现

commons-logging-1.2.jar
fastjson-1.2.6.jar
httpclient-4.5.jar
httpcore-4.4.4.jar
httpmime-4.5.jar
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Text?>

<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.layout.VBox?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1200.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MySceneController">
   <children>
      <Button fx:id="oneB" layoutX="684.0" layoutY="45.0" mnemonicParsing="false" onAction="#one" prefHeight="23.0" prefWidth="62.0" text="Send" />
      <TextField fx:id="ed" layoutX="374.0" layoutY="45.0" minWidth="300.0" promptText="需要http(s)://" />
      <TextArea fx:id="te" layoutX="547.0" layoutY="147.0" prefHeight="612.0" prefWidth="612.0" />

      <fx:define><ToggleGroup fx:id="tgType" /></fx:define>
      <RadioButton fx:id="getRadio" layoutX="402.0" layoutY="92.0" mnemonicParsing="false" selected="true"  toggleGroup="$tgType" text="GET"></RadioButton>
      <RadioButton fx:id="postRadio" layoutX="482.0" layoutY="92.0" mnemonicParsing="false" text="POST" toggleGroup="$tgType" />
      <RadioButton fx:id="putRadio" layoutX="571.0" layoutY="92.0" mnemonicParsing="false" text="PUT" toggleGroup="$tgType" />
      <RadioButton fx:id="deleteRadio" layoutX="657.0" layoutY="92.0" mnemonicParsing="false" text="DELETE" toggleGroup="$tgType" />

      <!--<Label fx:id="mess" layoutX="451.0" layoutY="116.0" text="请求次数" />-->
      <Text layoutX="350.0" layoutY="61.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Url" />
      <!--<Slider layoutX="522.0" layoutY="117.0" min="1.0" value="1.0" />-->
      <!--<Label layoutX="672.0" layoutY="116.0" text="1次" />-->
      <!--<Label layoutX="672.0" layoutY="116.0" text="1次" />-->
      <VBox fx:id="vbo" style="-fx-background-color: ivory" layoutX="27.0" layoutY="150.0" prefHeight="554.0" prefWidth="500.0" />
      <TextField fx:id="addkey" layoutX="103.0" layoutY="729.0" prefHeight="23.0" prefWidth="127.0" promptText="Key" />
      <Text layoutX="47.0" layoutY="745.0" strokeType="OUTSIDE" strokeWidth="0.0" text="添加" wrappingWidth="55.000001192092896" />
      <TextField fx:id="addvalue" layoutX="237.0" layoutY="729.0" promptText="Value" />
      <Button onAction="#sub" layoutX="412.0" layoutY="729.0" mnemonicParsing="false" text="确定" />
   </children>
</AnchorPane>

``
- MySceneController
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

public class MySceneController {


    @FXML
    private Button oneB;

    @FXML
    private TextField ed;

    @FXML
    private TextArea te;

    @FXML
    private RadioButton getRadio;

    @FXML
    private ToggleGroup tgType;

    @FXML
    private RadioButton postRadio;

    @FXML
    private RadioButton putRadio;

    @FXML
    private RadioButton deleteRadio;


    @FXML
    private VBox vbo;

    @FXML
    ToggleGroup t = new ToggleGroup();

    LinkedHashMap<String,String[]> map = new LinkedHashMap<>();

    SplitPane getP(String i,String k,String v){
        SplitPane p = new SplitPane();
        p.setDividerPositions(0.5);
        p.setPrefHeight(48.0);
        p.setPrefWidth(500.0);

        Label l = new Label(k+"   =    "+v);
        l.setPrefHeight(15.0);
        l.setPrefWidth(457.0);

        Button b = new Button("删除");
        b.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                System.out.println(i);

                remo(i);
            }
        });
        b.setMnemonicParsing(false);
        p.getItems().addAll(l,b);
        return p;
    }




    void sx(){
        vbo.getChildren().clear();
        vbo.setSpacing(5);
        Set<String> keys = map.keySet();   //此行可省略,直接将map.keySet()写在for-each循环的条件中
        for(String key:keys){
            vbo.getChildren().addAll(getP(map.get(key)[0],map.get(key)[1],map.get(key)[2]));
        }
    }



    void remo(String i){
        map.remove(i);
        sx();
    }




    int i = 1;
    @FXML
    void one(ActionEvent event) {
        String type = "GET";
        if (getRadio.selectedProperty().getValue()){
            te.setText(prettyJson(httpGet(ed.getText())));
        }
        if (postRadio.selectedProperty().getValue()){
            Set<String> keys = map.keySet();   //此行可省略,直接将map.keySet()写在for-each循环的条件中
            LinkedHashMap<String,String> map1 = new LinkedHashMap<>();
            for(String key:keys){
                map1.put(map.get(key)[1],map.get(key)[2]);
            }
            te.setText(prettyJson(httpPost(ed.getText(),map1)));
        }
        if (putRadio.selectedProperty().getValue()){
            Set<String> keys = map.keySet();   //此行可省略,直接将map.keySet()写在for-each循环的条件中
            LinkedHashMap<String,String> map1 = new LinkedHashMap<>();
            for(String key:keys){
                map1.put(map.get(key)[1],map.get(key)[2]);
            }
            te.setText(prettyJson(httpPut(ed.getText(),map1)));
        }
        if (deleteRadio.selectedProperty().getValue()){
            te.setText(prettyJson(httpDelete(ed.getText())));
        }



    }



    @FXML
    private TextField addkey;

    @FXML
    private TextField addvalue;
    @FXML
    void sub(ActionEvent event) {
        if(addkey.getText().equals("")||addvalue.getText().equals("")){}else {
            int i = new Random().nextInt(10000000) + 1;
            String[] lu = new String[3];
            lu[0]=i+"";
            lu[1]=addkey.getText();
            lu[2]=addvalue.getText();
            map.put(i + "", lu);
            addkey.setText("");
            addvalue.setText("");
            sx();
        }
    }

























    private String prettyJson(String json) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(json);
        } catch (Exception e) {
            return json;
        }
        return JSONObject.toJSONString(jsonObject, true);
    }

    static String httpPut(String url, Map map){
        String encode = "utf-8";
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        httpput.setHeader("Accept","*/*");
        httpput.setHeader("Accept-Encoding","gzip, deflate");
        httpput.setHeader("Cache-Control","no-cache");
        httpput.setHeader("Connection", "keep-alive");
        httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), encode);
        httpput.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            //响应信息
            httpResponse = closeableHttpClient.execute(httpput);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            closeableHttpClient.close();  //关闭连接、释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    static String httpPost(String url,Map map){
        // 返回body
        String body = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse=null;
        // 2、创建一个HttpPost请求
        HttpPost post = new HttpPost(url);
        // 5、设置header信息
        /**header中通用属性*/
        post.setHeader("Accept","*/*");
        post.setHeader("Accept-Encoding","gzip, deflate");
        post.setHeader("Cache-Control","no-cache");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/json;charset=UTF-8");



        // 设置参数
        if (map != null) {

            //System.out.println(JSON.toJSONString(map));
            try {
                StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8");
                entity1.setContentEncoding("UTF-8");
                entity1.setContentType("application/json");
                post.setEntity(entity1);

                // 7、执行post请求操作,并拿到结果
                httpResponse = httpClient.execute(post);
                // 获取结果实体
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    // 按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity, "UTF-8");
                }
                try {
                    httpResponse.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }
    static String httpGet(String url){
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse=null;
        String finalString = null;
        HttpGet httpGet = new HttpGet(url);
        /**公共参数添加至httpGet*/
/**header中通用属性*/
        httpGet.setHeader("Accept","*/*");
        httpGet.setHeader("Accept-Encoding","gzip, deflate");
        httpGet.setHeader("Cache-Control","no-cache");
        httpGet.setHeader("Connection", "keep-alive");
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");

        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            finalString= EntityUtils.toString(entity, "UTF-8");
            try {
                httpResponse.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return finalString;
    }

    public static String httpDelete(String url){

        //HttpResponse response = new HttpResponse();

        String encode = "utf-8";

        String content = null;
        //since 4.3 不再使用 DefaultHttpClient
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpDelete httpdelete = new HttpDelete(url);
        // 5、设置header信息

/**header中通用属性*/
        httpdelete.setHeader("Accept","*/*");
        httpdelete.setHeader("Accept-Encoding","gzip, deflate");
        httpdelete.setHeader("Cache-Control","no-cache");
        httpdelete.setHeader("Connection", "keep-alive");
        httpdelete.setHeader("Content-Type", "application/json;charset=UTF-8");


        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = closeableHttpClient.execute(httpdelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {   //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

}

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 * @ClassName: Main
 * @Auyher: WUX
 * @Date: 2020/5/18 13:34
 */
public class Main extends Application {
    static private Stage primaryStage;

//stack.getChildren().add(new Button("test")) ;
    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        Parent root = FXMLLoader.load(getClass().getResource("MySceneController.fxml"));
        primaryStage.setTitle("接口测试工具v1.0     QQ:724930341  欢迎指导");
        primaryStage.setScene(new Scene(root, 1200, 800));
        primaryStage.setResizable(false);//禁止缩放
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读