javafx之HTTP协议交互
来源:互联网 发布:淘宝网狗狗衣服 编辑:程序博客网 时间:2024/04/30 07:17
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); }}
- javafx之HTTP协议交互
- http协议以及交互
- 简析HTTP协议交互过程
- HTTP协议图片上传交互
- 交互须知的HTTP协议
- HTTP---Android 通过http协议数据交互
- javaFx与js交互
- Android 通过http协议数据交互
- Android 通过http协议数据交互
- http 协议的交互过程详细分析。
- 2,Android通过http协议数据交互
- 客户端与服务器交互---http协议
- HTTP协议格式和header、交互过程
- 客户端与服务端交互之socket与http协议的比较
- JSP协议之HTTP协议
- 协议系列之HTTP协议
- http协议之http响应
- HTTP协议之HTTP消息
- dup and dup2的剖析
- zuoye
- 浅谈大数据背景下的NUMA架构研究
- 完全卸载Oracle并重装
- Interface Trip Stop - SRS 报错
- javafx之HTTP协议交互
- 成功并不像你想像的那么难
- 深入探究函数返回局部变量
- php多态
- 扫描QR码
- 机房收费系统总结之4——VB.NET 轻松解决判断文本框、组合框为空问题
- Codeforces Round #119 (Div. 2) / 189A Cut Ribbon (完全背包)
- empty,isset,is_null比较(差异与异同)
- ubuntu安装MySQL