java類比 post/get方式發送資料 main方法中用的是post
import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;public class httpurl { private static final String TAG = "netUtils"; /** * 使用post方式登陸 * * @param username * @param password * @return */ public static void main(String []args){ httpurl test=new httpurl(); test.loginOfPost("niha","qwer1234"); } public static String loginOfPost(String username, String password) { HttpURLConnection conn = null; try { // 建立一個URL對象 URL mURL = new URL("http://localhost:12001"); // 調用URL的openConnection()方法,擷取HttpURLConnection對象 conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("POST");// 佈建要求方法為post /* conn.setReadTimeout(5000);// 設定讀取逾時為5秒 conn.setConnectTimeout(10000);// 設定串連網路逾時為10秒*/ conn.setDoOutput(true);// 設定此方法,允許向伺服器輸出內容 int len=0; String path="E:\\private_project\\github_project\\nsar\\test.txt"; // post請求的參數 byte[] buf= new byte[10240]; FileInputStream fis=new FileInputStream(path); while((len = fis.read(buf)) != -1){ System.out.print(len); }// String data = "username=" + username + "&password=" + password; // 獲得一個輸出資料流,向伺服器寫資料,預設情況下,系統不允許向伺服器輸出內容 OutputStream out = conn.getOutputStream();// 獲得一個輸出資料流,向伺服器寫資料// out.write(data.getBytes()); out.write(buf); out.flush(); out.close(); int responseCode = conn.getResponseCode();// 調用此方法就不必再使用conn.connect()方法 if (responseCode == 200) { InputStream is = conn.getInputStream(); String state = getStringFromInputStream(is); return state; } else {// Log.i(TAG, "訪問失敗" + responseCode); System.out.print("訪問失敗"); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect();// 關閉串連 } } return null; } /** * 使用get方式登陸 * * @param username * @param password * @return */ public static String loginOfGet(String username, String password) { HttpURLConnection conn = null; String data = "username=" + URLEncoder.encode(username) + "&password="+ URLEncoder.encode(password); String url = "http://192.168.0.100:8080/android/servlet/LoginServlet?"+ data; try { // 利用string url構建URL對象 URL mURL = new URL(url); conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); String state = getStringFromInputStream(is); return state; } else {// Log.i(TAG, "訪問失敗" + responseCode); System.out.print("訪問失敗"); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; } /** * 根據流返回一個字串資訊 * * @param is * @return * @throws IOException */ private static String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); // 模板代碼 必須熟練 byte[] buffer = new byte[1024]; int len = -1; // 一定要寫len=is.read(buffer) // 如果while((is.read(buffer))!=-1)則無法將資料寫入buffer中 while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } is.close(); String state = os.toString();// 把流中的資料轉換成字串,採用的編碼是utf-8(模擬器預設編碼) os.close(); return state; }}
java 類比伺服器端接收post/get資料 實現時不需要向用戶端返回資料,只需要接受用戶端發過來的資料 所以response 注釋掉了
import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;/** * Created by lpeiz on 2016/9/26. */public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(12001);// System.out.println("HTTP Server (only POST implemented) is ready and is listening on Port Number 12001 \n"); while(true) { Socket clientSocket = serverSocket.accept();// System.out.println(clientSocket.getInetAddress().toString() + " " + clientSocket.getPort()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));// OutputStream out = clientSocket.getOutputStream(); String temp; int i=1001; while((temp=in.readLine()) != null) System.out.println(temp+i++);// String response = "HTTP/1.1 200 OK\n\r";// response = response + "Date: Fri, 04 May 2001 20:08:11 GMT\n\r";// response = response + "Server: Sanjits Server\n\r";// response = response + "Connection: close\n\r";// response = response + "1";// byte[] bytes = response.getBytes();// byte[]bytes=new byte[1024];// out.write(bytes);// out.flush(); in.close();// out.close(); } } catch(Exception e) { System.out.println("ERROR: " + e.getMessage()); System.exit(1); }}}
國慶節前看了一個案例 但是跑的時候發現是錯誤的 13年前的文章,現在還用這計數也確實該多學點先進的技術了
https://coderanch.com/t/205623/java/Java-Http-Server-Java-Http
對用戶端的程式參照網上找到的其他成功的程式 改造了一下,加了兩行發現成功了。。。
con.setReadTimeout(5000);// 設定讀取逾時為5秒 con.setConnectTimeout(10000);// 設定串連網路逾時為10秒
就是這個控制時間的兩行,還沒搞清楚為什麼。可能是類似jdbc串連的時候的語句執行之後的重新整理問題
public class Client { public static void main(String[] args) { try { URL url = new URL("http://localhost:12001"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true);// con.setDoInput(true); con.setRequestMethod("POST");// con.setUseCaches(false); con.setReadTimeout(5000);// 設定讀取逾時為5秒 con.setConnectTimeout(10000);// 設定串連網路逾時為10秒 String test = "<name>Hello</name>"; byte[] bytes = test.getBytes();// con.setRequestProperty("Content-type", "text/html"); OutputStream out = con.getOutputStream(); out.write(bytes); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String temp; while((temp = in.readLine()) != null) System.out.println(temp);// out.close(); in.close(); con.disconnect(); } catch(Exception e) { e.printStackTrace(); System.exit(1);}}}