javafx之HTTP协议交互

javafx端要获取获取如下信息:


服务器端获取的数据:


javafx客户端发送的数据以及获取的数据:


工程目录:


package Httputil;

import IPsite.IPaddress;
import Streamutil.StreamTool;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Legend-novo
 */
public class HttpMethod {
    
    /**
     * GET方式获取字符串
     * @return  返回字符串
     * @throws Exception 
     */
	public static String getGETString() throws Exception{
		URL url = new URL(IPaddress.IP_get_SITE);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
                conn.setDoOutput(true);
                conn.setDoInput(true);
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			byte[] data = StreamTool.read(inputStream);
			return new String(data);
		}
		return null;
	}
        /**
         * 以GET方式发送字符串
         * @param params 要发送的数组
         * @param encoding  发送的编码
         * @return  true返回成功,false返回失败
         * @throws Exception 
         */
        public static boolean  sendGETString(HashMap<String,String> params,String encoding) throws Exception{
		StringBuilder url = new StringBuilder(IPaddress.IP_send_SITE);
		url.append("?");
		for (Map.Entry<String,String> entry: params.entrySet()) {
			url.append(entry.getKey()).append("=");
			url.append(URLEncoder.encode(entry.getValue(), encoding));
			url.append("&");
		}
		url.deleteCharAt(url.length()-1);
		HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			return true;
		}
		return false;
        }
        
     /**
     * POST方式获取字符串
     * @return  返回字符串
     * @throws Exception 
     */
	public static String getPOSTString() throws Exception{
		URL url = new URL(IPaddress.IP_get_SITE);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
                conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
                conn.setDoOutput(true);
                conn.setDoInput(true);
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			byte[] data = StreamTool.read(inputStream);
			return new String(data);
		}
		return null;
	}
        /**
         * 以POST方式发送字符串
         * @param params 要发送的数组
         * @param encoding  发送的编码
         * @return  true返回成功,false返回失败
         * @throws Exception 
         */
        public static boolean  sendPOSTString(HashMap<String,String> params,String encoding) throws Exception{
        StringBuilder data = new StringBuilder();
        if (params != null && !params.isEmpty()) {
                for (Map.Entry<String,String> entry: params.entrySet()) {
                        data.append(entry.getKey()).append("=");
                        data.append(URLEncoder.encode(entry.getValue(), encoding));
                        data.append("&");
                }
                data.deleteCharAt(data.length()-1);
        }
        byte[] entity = data.toString().getBytes();//得到实体数据
        HttpURLConnection conn = (HttpURLConnection) new URL(IPaddress.IP_send_SITE).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);//允许对外输出数据
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
        OutputStream oStream = conn.getOutputStream();
        oStream.write(entity);
        if(conn.getResponseCode() == 200){//用于获得返回数据才能发送数据,不然数据一直在缓存数据中
                return true;
        }
        return false;
}
}

package IPsite;

/**
 *
 * @author Legend-novo
 */
public class IPaddress {
    public static final String IP_get_SITE = "http://192.168.1.100:8080/JavaFXtest/JavaFXServlet";         //接受信息的IP地址
    public static final String IP_send_SITE = "http://192.168.1.100:8080/JavaFXtest/JavaFxgetServlet";    //发送信息的IP地址
}

package JsonMethod;

import Person.personbean;
import java.util.List;

/**
 *
 * @author Legend-novo
 */
public class JsonStr {
    public static String getJson(List<personbean> person){
        if(person.isEmpty()){
        System.out.println("传入对象为空!");
        }else{
        StringBuilder json = new StringBuilder();
        if (person.size()==1) {
                json.append("{\"name\":\"");
                json.append(person.get(0).getName());
                json.append("\",\"age\":\"");
                json.append(person.get(0).getAge());
                json.append("\"}");
        }else {
                json.append("[");
                for (int i = 0; i < person.size(); i++) {
                json.append("{\"name\":\"");
                json.append(person.get(i).getName());
                json.append("\",\"age\":\"");
                json.append(person.get(i).getAge());
                if (i <(person.size()-1)) {
                        json.append("\"},");
                }else {
                        json.append("\"}");
                }
          }
                json.append("]");
        }
        return json.toString();
        }
        return null;
    }
}

package Person;

/**
 *
 * @author Legend-nov
 */
public class personbean {
    private String name;
    private Integer age;
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the age
     */
    public Integer getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(Integer age) {
        this.age = age;
    }
    public personbean(){}
    public personbean(String name,Integer age){
    this.name = name;
    this.age = age;
    }
}

package Streamutil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 *
 * @author Legend-novo
 */
public class StreamTool {
    	/**
	 * 读取流中的数据
	 * @param stream 传入的流
	 * @return
	 * @throws Exception
	 */
	public static byte[] read(InputStream stream) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len=stream.read(buffer)) != -1){
			outputStream.write(buffer, 0, len);
		}
		return outputStream.toByteArray();
	}
}

package httptest;

import Httputil.HttpMethod;
import JsonMethod.JsonStr;
import Person.personbean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author Legend-novo
 */
public class HttpTest extends Application {
    private String message = null;
    /**
     * 将对象转换成JSON对象数据
     * @return 返回JSON对象数据
     */
    public String setJson(){
        personbean person1 = new personbean("zhangsan",21);
        personbean person2 = new personbean("lisi",25);
        personbean person3 = new personbean("tom",31);
        final List<personbean> list = new ArrayList<>();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        return JsonStr.getJson(list);
    }
    /**
     * 以GET的方式进行数据交互
     * @param primaryStage 
     */
    public void GETHttp(Stage primaryStage){

        final HashMap<String,String> map = new HashMap<>();
         map.put("data",setJson());
         System.out.println(setJson());
        
        final Label labelget = new Label();
        final Label labelsend = new Label();
        Button btnget = new Button();
        btnget.setText("获取信息");
        Button btnsend = new Button();
        btnsend.setText("发送信息");
        btnget.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("点击了btnget!");
                try {
                    message = HttpMethod.getGETString();
                    labelget.setText(message);
                } catch (Exception ex) {
                    Logger.getLogger(HttpTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        
         btnsend.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("点击了btnsend!");
                try {
                    if(HttpMethod.sendGETString(map, "UTF-8")){
                        labelsend.setText("sending successed");
                    }else{
                        labelsend.setText("sending failed");
                    }
                } catch (Exception ex) {
                    Logger.getLogger(HttpTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        VBox vb = new VBox(10);
        vb.getChildren().addAll(btnget,labelget,btnsend,labelsend);
        StackPane root = new StackPane();
        root.getChildren().add(vb);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("GET方式数据交互");
        primaryStage.setScene(scene);
    }
    
     public void POSTHttp(Stage primaryStage){

        final HashMap<String,String> map = new HashMap<>();
         map.put("data",setJson());
         System.out.println(setJson());
        
        final Label labelget = new Label();
        final Label labelsend = new Label();
        Button btnget = new Button();
        btnget.setText("获取信息");
        Button btnsend = new Button();
        btnsend.setText("发送信息");
        btnget.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("点击了btnget!");
                try {
                    message = HttpMethod.getPOSTString();
                    labelget.setText(message);
                } catch (Exception ex) {
                    Logger.getLogger(HttpTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        
         btnsend.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("点击了btnsend!");
                try {
                    if(HttpMethod.sendGETString(map, "UTF-8")){
                        labelsend.setText("sending successed");
                    }else{
                        labelsend.setText("sending failed");
                    }
                } catch (Exception ex) {
                    Logger.getLogger(HttpTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        VBox vb = new VBox(10);
        vb.getChildren().addAll(btnget,labelget,btnsend,labelsend);
        StackPane root = new StackPane();
        root.getChildren().add(vb);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("POST方式数据交互");
        primaryStage.setScene(scene);
    }
    @Override
    public void start(Stage primaryStage) {
//        POSTHttp(primaryStage);
        GETHttp(primaryStage);
        primaryStage.show();
    }

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


  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值