本示例源於爲朋友解決一個小問題,數據庫到服務器的數據傳輸,因爲本人能力有限,暫時將它理解爲從數據庫中獲取數取表數據,實際上有多是文件或者其餘形式的數據,不過原理都得用流傳輸,javascript
首先httpclientjava
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¶m2=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(); } }}