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);
}
}
javafx之HTTP协议交互的更多相关文章
- springBoot -webSocket 基于STOMP协议交互
浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打破了 ...
- SNMP协议交互学习-获取udp的udpindatagrams
MIB的组织结构,如下左图,对于udp来说1.3.6.1.2.1.7,组织如下右图,包括4个标量和1个表格 udp节点在LwIP中的定义如下: ] = { , , , , }; ] = { (stru ...
- dhcp协议交互报文
DHCP共有八种报文,分别为DHCP Discover.DHCP Offer.DHCP Request.DHCP ACK.DHCP NAK.DHCP Release.DHCP Decline.DHCP ...
- ajax与一般处理程序 HTTP协议交互
1,一般处理程序中 context.Response.ContentType = "text/plain", 则 ajax参数中 也是 text 类型. 2,一般处理程序中 转化 ...
- HTTP协议系列(1)
一.为什么学习Http协议 首先明白我们为什么学习HTTP协议,也就是说明白HTTP协议的作用.HTTP协议是用于客户端与服务器之间的通讯.明白了HTTP协议的作用也就知道了为什么要学习H ...
- RTSP协议媒体数据发包相关的细节
最近完成了一RTSP代理网关,这是第二次开发做RTSP协议相关的开发工作了,相比11年的简单粗糙的版本,这次在底层TCP/IP通讯和RTSP协议上都有了一些新的积累,这里记录一下.基本的RTSP协议交 ...
- Memcache的使用和协议分析详解
Memcache的使用和协议分析详解 作者:heiyeluren博客:http://blog.csdn.NET/heiyeshuwu时间:2006-11-12关键字:PHP Memcache Linu ...
- RTMP协议中文翻译(首发)(转)
Adobe公司的实时消息传输协议 摘要 此备忘录描述了 Adobe公司的实时消息传输协议(RTMP),此协议从属于应用层,被设计用来在适合的传输协议(如TCP)上复用和打包多媒体传输流(如音频.视频和 ...
- JAVA的UDP协议交互信息
由于要做app的UDP协议交互,所以就特地学习了下,其实也就类似于java的server和socket,下面就写了个简单的demo 服务端: package com.test1; import jav ...
随机推荐
- .net连接DB2的异常SQL0666 - SQL query exceeds specified time limit or storage limit.错误处理
SQL0666 - SQL query exceeds specified time limit or storage limit. 原因:查询超时 解决办法: set the DbCommand.C ...
- 基于Python的网页文档处理脚本实现
嵌入式web服务器不同于传统服务器,web需要转换成数组格式保存在flash中,才方便lwip网络接口的调用,最近因为业务需求,需要频繁修改网页,每次的压缩和转换就是个很繁琐的过程,因此我就有了利用所 ...
- js_多个引号的用法
str += "<input id='sel_DayB' width='120' onfocus=\"WdatePicker({skin:'whyGreen',dateFmt ...
- 两个list 合并成新一个list
- contiki-事件调度
事件驱动机制广泛应用于嵌入式系统,类似于中断机制,当有事件到来时(比如按键.数据到达),系统响应并处理该事件.相对于轮询机制,事件机制优势很明星,低功耗(系统处于休眠状态,当有事件到达时才被唤醒)和M ...
- 《开源安全运维平台:OSSIM最佳实践》内容简介
<开源安全运维平台:OSSIM最佳实践 > 李晨光 著 清华大学出版社出版 内 容 简 介在传统的异构网络环境中,运维人员往往利用各种复杂的监管工具来管理网络,由于缺乏一种集成安全运维平台 ...
- InventSumDelta表的作用
https://groups.google.com/forum/#!topic/microsoft.public.axapta.programming/rRfbJo9M0dk The purpose ...
- js数组倒叙输出
第一种:是直接利用代码进行输出 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"&g ...
- js判断数据类型
1.判断一个数字是否是无穷的 isFinite()例:var aa=Number.POSITIVE_INFINITY; if(isFinite(aa)){ alert("aa不是无穷的&qu ...
- jsexcel导出插件
ExcelTable.js /* * author:wenluanlai */ (function ($) { Date.prototype.Format = function (fmt) { var ...