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协议交互的更多相关文章

  1. springBoot -webSocket 基于STOMP协议交互

    浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打破了 ...

  2. SNMP协议交互学习-获取udp的udpindatagrams

    MIB的组织结构,如下左图,对于udp来说1.3.6.1.2.1.7,组织如下右图,包括4个标量和1个表格 udp节点在LwIP中的定义如下: ] = { , , , , }; ] = { (stru ...

  3. dhcp协议交互报文

    DHCP共有八种报文,分别为DHCP Discover.DHCP Offer.DHCP Request.DHCP ACK.DHCP NAK.DHCP Release.DHCP Decline.DHCP ...

  4. ajax与一般处理程序 HTTP协议交互

    1,一般处理程序中 context.Response.ContentType = "text/plain", 则  ajax参数中 也是 text 类型. 2,一般处理程序中 转化 ...

  5. HTTP协议系列(1)

    一.为什么学习Http协议       首先明白我们为什么学习HTTP协议,也就是说明白HTTP协议的作用.HTTP协议是用于客户端与服务器之间的通讯.明白了HTTP协议的作用也就知道了为什么要学习H ...

  6. RTSP协议媒体数据发包相关的细节

    最近完成了一RTSP代理网关,这是第二次开发做RTSP协议相关的开发工作了,相比11年的简单粗糙的版本,这次在底层TCP/IP通讯和RTSP协议上都有了一些新的积累,这里记录一下.基本的RTSP协议交 ...

  7. Memcache的使用和协议分析详解

    Memcache的使用和协议分析详解 作者:heiyeluren博客:http://blog.csdn.NET/heiyeshuwu时间:2006-11-12关键字:PHP Memcache Linu ...

  8. RTMP协议中文翻译(首发)(转)

    Adobe公司的实时消息传输协议 摘要 此备忘录描述了 Adobe公司的实时消息传输协议(RTMP),此协议从属于应用层,被设计用来在适合的传输协议(如TCP)上复用和打包多媒体传输流(如音频.视频和 ...

  9. JAVA的UDP协议交互信息

    由于要做app的UDP协议交互,所以就特地学习了下,其实也就类似于java的server和socket,下面就写了个简单的demo 服务端: package com.test1; import jav ...

随机推荐

  1. Qt编程'""hello world

    #include<QApplication>#include<QLabel>int main(int argc,char*argv[]){QApplicatin app(arg ...

  2. Hook机制里登场的角色

    稍有接触过 WordPress 主题或插件制作修改的朋友,对 WordPress 的Hook机制应该不陌生,但通常刚接触WordPress Hook 的新手,对其运作原理可能会有点混乱或模糊.本文针对 ...

  3. PHP基础知识之————PHP Web脚本中使用FFmpeg

    简介 本文将尝试指出在PHP Web脚本中使用FFmpeg时需要了解的所有重要事项.它还将显示一些使用示例,以使事情更清楚.这个想法也可以应用到其他web脚本语言. 从PHP脚本调用命令行工具 选择一 ...

  4. SwitchyOmega 在线调试

    1,chrome 安装 Proxy SwitchyOmega 扩展程序 2,新建情景模式,输入模式名称"例如:new proxy1",选择"请选择情景模式的类型:代理服务 ...

  5. hostapd与wpa_supplicant

    hostapd与wpa_supplicant hostapd hostapd includes IEEE 802.11 access point management (authentication ...

  6. 构建高可用集群Keepalived+Haproxy负载均衡

    重点概念vrrp_script中节点权重改变算法vrrp_script 里的script返回值为0时认为检测成功,其它值都会当成检测失败:weight 为正时,脚本检测成功时此weight会加到pri ...

  7. 关于启用 HTTPS 的一些经验分享(二)

    转载: 关于启用 HTTPS 的一些经验分享(二) 几天前,一位朋友问我:都说推荐用 Qualys SSL Labs 这个工具测试 SSL 安全性,为什么有些安全实力很强的大厂家评分也很低?我认为这个 ...

  8. 设置git 不提交 修改权限的文件

    vim .git/config  打开文件

  9. block,inline和inlinke-block细节对比

    block,inline和inlinke-block细节对比 display:block block元素会独占一行,多个block元素会各自新起一行.默认情况下,block元素宽度自动填满其父元素宽度 ...

  10. express+gulp构建项目(五)swig模板

    这里的文件负责配置swig模板引擎. index.js var jsonHash = require('./json_file'); var staticTag = require("./t ...