HttpUrlConnection以GET方式和POST方式請求伺服器
阿新 • • 發佈:2019-01-03
1:GET方式。這種方式比較簡單,直接在URL後面加上引數即可
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpUrlCon {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/myhome/mypage/JasonTest.do?userName=liufukin");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// //設定連線屬性
httpConn.setRequestMethod("GET");// 設定URL請求方法,預設為“GET”
httpConn.setDoOutput(false );// 禁止 URL 連線進行輸出,預設為“false”
httpConn.setDoInput(true);// 使用 URL 連線進行輸入,預設為“true”
httpConn.setUseCaches(false);// 忽略快取
// 設定 《請求頭》資訊
httpConn.setRequestProperty("accept", "*/*");
httpConn.setRequestProperty("Content-Type", "application/octet-stream" ); //設定的文字型別,此欄位必須和和伺服器端處理請求流的編碼一致,否則無法解析
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連線
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("BrokerID", URLEncoder.encode("MFTST0", "utf-8"));
// 前面的操作只是將“請求頭”和“正文”組裝成request物件,最後真正以HTTP協議傳送資料的是下面的getInputStream();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
System.out.println(responseReader.readLine());
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
2:POST請求。其實和GET差不多,只是他的引數部分需要以“字元流”的形式處理,在和之前的“請求頭”部分資訊組裝成request物件在傳送過去。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpUrlCon {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/myhome/mypage/JasonTest.do");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// //設定連線屬性
httpConn.setRequestMethod("POST");// 設定URL請求方法,預設為“GET”
httpConn.setDoOutput(true);// 使用 URL 連線進行輸出,預設為“false”
httpConn.setDoInput(true);// 使用 URL 連線進行輸入,預設為“true” httpConn.setUseCaches(false);// 忽略快取
// 設定 《請求頭》資訊
httpConn.setRequestProperty("accept", "*/*");
httpConn.setRequestProperty("Content-Type", "application/octet-stream"); //設定的文字型別,此欄位必須和和伺服器端處理請求流的編碼一致,否則無法解析
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連線
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("BrokerID", URLEncoder.encode("MFTST0", "utf-8"));
//傳送正文context;其實並非傳送,而是將其儲存在快取中,最後和前面設定的“請求頭”組裝成request物件
ObjectOutputStream objOutputStrm = new ObjectOutputStream(httpConn.getOutputStream());
objOutputStrm.writeObject("userName=liufu & pwd=815325"); // 這裡傳送一個空資料
objOutputStrm.flush();
objOutputStrm.close();
// 前面的操作只是將“請求頭”和“正文”組裝成request物件,最後真正以HTTP協議傳送資料的是下面的getInputStream();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
System.out.println(responseReader.readLine());
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
由於經常需要對建立和封裝HTTP請求,所以可以把它們整合起來,呼叫即可產生httpurlconnection物件。
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HttpUrlCon {
// URL url = new URL("http://192.168.7.127:3000/system/brokers?langCode=zh_CN&ordChnl=M");
// URL url = new URL("http://192.168.7.130:8080/loadrunnerServer/mypage/dologin.do");
// URL url = new URL("http://192.168.7.127:3000/clients/026200000/session");
static HashMap<String, String> commonHashmap = new HashMap<String, String>();
public static void main(String[] args) {
HashMap<String, String> hashMapHead = new HashMap<String, String>();//包含“請求頭”的資訊
hashMapHead.put("Content-Type", "application/x-www-form-urlencoded");
hashMapHead.put("Charset", "UTF-8");
hashMapHead.put("Connection", "Keep-Alive");
hashMapHead.put("BrokerID", "MFTST0");
HashMap<String, String> hashMapBody = new HashMap<String, String>();//包含“請求正文(body)”的資訊
hashMapBody.put("password", "123456789");
hashMapBody.put("ordChnl", "M");
String urlString = "http://192.168.7.127:3000/clients/026200000/session";
HttpUrlCon httpUrlCon = new HttpUrlCon();
HttpURLConnection httpURLConn = httpUrlCon.createPOSTHttpconn(urlString, hashMapHead, hashMapBody);
if(httpURLConn != null){
BufferedReader bufferedReader = null;
try {
if(HttpURLConnection.HTTP_OK == httpURLConn.getResponseCode()){
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream(),"UTF-8"));
if(bufferedReader.readLine().contains("\"status\":\"S\"")){
commonHashmap.put("authorization", httpURLConn.getHeaderField("authorization"));
httpUrlCon.getOrders();
}
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void getOrders(){
HashMap<String, String> hashMapHead = new HashMap<String, String>();//包含“請求頭”的資訊
hashMapHead.put("Charset", "UTF-8");
hashMapHead.put("authorization", commonHashmap.get("authorization"));
hashMapHead.put("BrokerID", "MFTST0");
HashMap<String, String> hashMapBody = new HashMap<String, String>();//包含“請求正文(body)”的資訊
hashMapBody.put("from", "2012-01-31Z");
String urlString = "http://192.168.7.127:3000/accounts/0262000001011/orders";
HttpURLConnection httpURLConn = new HttpUrlCon().createGetHttpConn(urlString, hashMapHead, hashMapBody);
if(httpURLConn != null){
BufferedReader bufferedReader = null;
try {
if(HttpURLConnection.HTTP_OK == httpURLConn.getResponseCode()){
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream(),"UTF-8"));
System.out.println(bufferedReader.readLine());
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public HttpURLConnection createGetHttpConn(String urlString, HashMap<String, String> hashMapHead, HashMap<String, String> hashMapBody){
HttpURLConnection httpConn = null;
//根據hashMapBody組裝需要傳給後臺的引數,只是以GET的形式傳送的話,把他放在URL後面即可
StringBuffer paramStr = new StringBuffer();
if(hashMapBody != null){
Iterator<Map.Entry<String, String>> iterator = hashMapBody.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
paramStr.append(entry.getKey()+ "=" + entry.getValue() + "&");
}
if(!paramStr.toString().trim().equals("")){
paramStr.deleteCharAt(paramStr.length()-1);
urlString += "?" + paramStr;
}
}
try {
URL url = new URL(urlString);
httpConn = (HttpURLConnection) url.openConnection();
// 根據hashMapHead組裝《請求頭》資訊
if(hashMapHead != null){
Iterator<Map.Entry<String, String>> iterator = hashMapHead.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return httpConn;
}catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public HttpURLConnection createPOSTHttpconn(String urlString, HashMap<String, String> hashMapHead, HashMap<String, String> hashMapBody){
HttpURLConnection httpConn = null;
//根據hashMapBody拼接需要傳送給後臺的正文(body),這個是post形式傳送,所以得要用outputstream來發送。
StringBuffer paramStr = new StringBuffer();
if(hashMapBody != null){
Iterator<Map.Entry<String, String>> iterator = hashMapBody.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
paramStr.append(entry.getKey() + "=" + entry.getValue() + "&");
}
if(!paramStr.toString().trim().equals("")){
paramStr.deleteCharAt(paramStr.length()-1);
}
}
try {
URL url = new URL(urlString);
httpConn = (HttpURLConnection) url.openConnection();
// 設定連線屬性
httpConn.setDoOutput(true);// 使用 URL 連線進行輸出 ,預設為false
httpConn.setDoInput(true);// 使用 URL 連線進行輸入 ,預設為true
httpConn.setUseCaches(false);// 忽略快取
httpConn.setRequestMethod("POST");// 設定URL請求方法
// 根據hashMapHead組裝《請求頭》資訊
if(hashMapHead != null){
Iterator<Map.Entry<String, String>> iterator = hashMapHead.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
//設定業務邏輯需要傳送過去的欄位
DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
out.writeBytes(paramStr.toString());
out.flush();
out.close();
return httpConn;
}catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
總結:GET和post主要的差別是一個在URL後面接引數,而另一個是以正文內容的形式傳送給伺服器端。特別要注意的是:以post方式發起請求的時候,那個“請求頭”的hashMapHead.put(“Content-Type”, “application/x-www-form-urlencoded”);一定要和後臺伺服器的匹配上才行,否則傳過去給伺服器的引數無法被解析出來,會發現為null。(注意啊!!!)