本示例源于为朋友解决一个小问题,数据库到服务器的数据传输,由于本人能力有限,暂时将它理解为从数据库中获取数取表数据,实际上有可能是文件或者其他形式的数据,不过原理都得用流传输,

首先httpclient

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import netscape.javascript.JSObject; import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by jisen on 2018/5/24.
*/
public class Httpclient {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
String dataByJDBC = getDataByJDBC();
//如果不从数据库取直接发送字符串
//String dataByJDBC="hello httpserver";
String backData = httpPost(dataByJDBC); System.out.println(backData);
} //获取数据库的数据并封装成json字符串
public static String getDataByJDBC() throws ClassNotFoundException, SQLException { String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/admin?useSSL=false";
String username = "root";
String password = "root";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password); //从数据库中获取数据
String sql = "select * from menu";
PreparedStatement preparedStatement = connection.prepareStatement(sql);//预处理说起来 ResultSet resultSet = preparedStatement.executeQuery();
int columnCount = resultSet.getMetaData().getColumnCount();
ResultSetMetaData metaData = resultSet.getMetaData();
Map<String,Object> dataMap = new HashMap<String,Object>();
List<Map<String,Object>> list = new ArrayList<>();
while (resultSet.next()){
for(int i=1 ; i<=columnCount;i++){
String columnName = metaData.getColumnName(i);
Object object = resultSet.getObject(i);
dataMap.put(columnName,object);
}
list.add(dataMap);
} String jsonString = JSON.toJSONString(list);
System.out.println(jsonString);
return jsonString;
} public static String httpGet() throws IOException {
URL url = new URL("http://localhost:8080/httpServer?param1=jisen&param2=jisen2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
//接收反馈
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine())!=null){
sBuffer.append(line).append("\r\n");
}
reader.close();
return sBuffer.toString();
} public static String httpPost(String data) throws IOException {
URL url = new URL("http://localhost:8080/httpServer");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//HttpURLConnection中的doInput默认为true,而doOutput默认为false,所以如果需要些内容到流,需要设置为true
conn.setDoOutput(true);
conn.connect();
//写入流,发送Http请求
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
conn.getOutputStream()));
writer.write(data);
writer.flush(); //接收反馈
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(),"utf8"));
StringBuffer sBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sBuffer.append(line).append("\r\n");
}
reader.close();
return sBuffer.toString();
}
} 其次httpserver
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.HashMap;
import java.util.Map; /**
* Created by jisen on 2018/5/24.
*/
public class MyHttpServer { public static void main(String[] args) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080),10);
httpServer.createContext("/httpServer", new MyHandler());
httpServer.setExecutor(null);
httpServer.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange he) throws IOException { InputStream is = he.getRequestBody();
//接收反馈
BufferedReader reader = new BufferedReader(new InputStreamReader(
is,"utf8")); StringBuffer sBuffer = new StringBuffer(); String line = "";
while ((line = reader.readLine()) != null) {
sBuffer.append(line).append("\r\n");
}
reader.close();
is.close();
System.out.println("接收到来自数据库的数据");
System.out.println(sBuffer);
//服务器收到
String response = "the data is receive";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
												

http通信示例Httpclient和HttpServer的更多相关文章

  1. android http 通信(httpclient 实现)

    1.httpclient get 方式 HttpGet httpGet = new HttpGet(url); HttpClient client = new DefaultHttpClient(); ...

  2. C#上位机之—WinForm实现串口通信示例

    上位机开发常用到串口通信来控制设备,串口通信的主要参数:COM口,波特率(9600),停止位(One),数据位(8),校验位(None),括号中的是常用值,具体意思我也不太懂,会用能实现功能就行哈哈: ...

  3. [ActionScript 3.0] 两个AIR之间的通信示例LocalConnection

    发送方AIR程序: package { import flash.display.DisplayObjectContainer; import flash.display.Sprite; import ...

  4. 使用AF_INET实现点对点的通信示例

    作者:Younger Liu,本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 未本地化版本许可协议进行许可. 1.    客户端(发送方) 操作流如下: (1) 使用AF_INET协议簇, ...

  5. lua 中 socket 通信示例

    server.lua #!/usr/bin/lua local socket = require("socket") host, port = "127.0.0.1&qu ...

  6. Java Socket通信示例

    Socket分为ServerSocket和Socket两大类: 其中ServerSocket用于服务器端,可以通过accept方法监听请求,监听到请求后返回Socket: Socket用户具体完成数据 ...

  7. Windows7下驱动开发与调试体系构建——2.R3与R0的通信示例

    目录/参考资料:https://www.cnblogs.com/railgunRG/p/14412321.html 在阅读本节前,建议先阅读<Windows内核安全与驱动开发>第五章内容, ...

  8. java netty socket库和自定义C#socket库利用protobuf进行通信完整实例

    之前的文章讲述了socket通信的一些基本知识,已经本人自定义的C#版本的socket.和java netty 库的二次封装,但是没有真正的发表测试用例. 本文只是为了讲解利用protobuf 进行C ...

  9. iOS开发多线程篇—线程间的通信

    iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...

随机推荐

  1. python-机器学习-深度学习-算法-面试题

    GitHub 地址: https://github.com/taizilongxu/interview_python https://github.com/imhuay/Algorithm_Inter ...

  2. [LeetCode] 280. Wiggle Sort 摆动排序

    Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] < ...

  3. [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  4. odoo - 自定义默认主页

  5. Java开发笔记(一百三十三)Swing的菜单

    传统的桌面程序基本是对某种类型的文件进行加工,例如Window自带的记事本用来读写文本文件,自带的画图程序用来查看和修改位图文件.为了方便用户切换各种操作,这些程序在窗口顶端放了一排菜单栏,单击菜单栏 ...

  6. Django django.core.exceptions.ImproperlyConfigured: WSGI application 'myblog.wsgi.application' could not be loaded; Error importing module.报错

    报错内容 django.core.exceptions.ImproperlyConfigured: WSGI application 'myblog.wsgi.application' could n ...

  7. Spring RestTemplate的使用示例

    @Bean注册一个RestTemplate: 调用服务: 因为要参与网络传输,所以要实现序列化接口:

  8. quartz2.3.0(五)制定错过执行任务的misfire策略,用pause,resume模拟job暂停执行和继续执行

    感谢兄台: <quartz-misfire 错失.补偿执行> misfire定义 misfire:被错过的执行任务策略 misfire重现——CronTrigger job任务类: pac ...

  9. JDK并发的类

    Future : 提前完成任务 原理:wait(),notify()的使用. 线程之间的通信 : CountDownLatch :线程计数 CyclicBarrier :循环计数 Semaphore ...

  10. [洛谷P5304][GXOI/GZOI2019]旅行者

    题目大意: 有一张 \(n(n\leqslant10^5)\) 个点 \(m(m\leqslant5\times10^5)\) 条边的有向有正权图,有$k(2\leqslant k\leqslant ...