從表面來看GET和POST請求:java
GET請求是在url後直接附上請求體,url和請求體之間用"?"分割,不一樣參數之間用"&"分隔,%XX中的XX爲該符號以16進製表示的ASCII,若是數據是英文字母/數字,原樣發送,若是是空格,轉換爲+,若是是中文/其餘字符,則直接把字符串用BASE64加密。api
POST把提交的數據則放置在是HTTP包的包體中,Post沒有限制提交的數據。Post比Get安全,當數據是中文或者不敏感的數據,則用get,由於使用get,參數會顯示在地址,對於敏感數據和不是中文字符的數據,則用post
安全
Java中get請求:app
package com.httpGetTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpGetTest { public static void main(String[] args) { CreatHttpUrl creatUrl = new CreatHttpUrl(); String url = CreatHttpUrl.creatUrl("teacher", "en", "zh-CHS"); //System.out .print(url); // new readByGet().start(); readData(); } public static void readData() { try { CreatHttpUrl creatUrl = new CreatHttpUrl(); String urlStr = CreatHttpUrl.creatUrl("teacher", "en", "zh-CHS"); URL url = new URL(urlStr); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader bf = new BufferedReader(isr); String line; StringBuilder builder = new StringBuilder(); while((line = bf.readLine()) != null) { builder.append(line); } bf.close(); isr.close(); is.close(); System.out.println(builder); } catch (Exception e) { e.printStackTrace(); } } }
Java中的post請求:post
package com.httpPostTest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpPostTest { public static void main(String[] args) { CreatHttpUrl creatUrl = new CreatHttpUrl(); String urlStr = "https://openapi.youdao.com/api"; String paramStr = creatUrl.createParam("good","en","zh-CHS"); System.out.println(paramStr); try { //設置請求相關設置 URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("encoding", "UTF-8"); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); //post提交數據 OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter writer = new BufferedWriter(osw); writer.write(paramStr); writer.flush(); //讀取獲取的數據 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder builder = new StringBuilder(); while((line = br.readLine()) != null) { builder.append(line); } writer.close(); osw.close(); os.close(); br.close(); isr.close(); is.close(); System.out.print(builder.toString()); } catch (Exception e) { e.printStackTrace(); } } }