HttpURLConnection GET和POST請求調用遠程接口
package com.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
useGetMethod("http://127.0.0.1:8080/getData");
usePostMethod("http://127.0.0.1:8080/getData");
}
public static Map<String,Object> useGetMethod(String get_url){
try {
Map<String,Object> result = new HashMap<String,Object>();
URL url = new URL(get_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//設置連接遠程服務器的超時時間
connection.setConnectTimeout(30000);
//設置讀取遠程返回的數據時間
connection.setReadTimeout(30000);
//設置請求參數的數據格式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuffer str = new StringBuffer();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
try{
String line = "";
while((line = br.readLine()) != null) {
str.append(line);
}
} finally {
br.close();
in.close();
}
JSONObject jsonObject = new JSONObject(str.toString());
result.put("code", jsonObject.get("code"));
result.put("message", jsonObject.get("message"));
}else{
System.out.println("錯誤狀態碼:"+responseCode);
result.put("code", responseCode);
result.put("message", "異常");
}
connection.disconnect();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Map<String,Object> usePostMethod(String post_url){
try {
Map<String,Object> result = new HashMap<String,Object>();
URL url = new URL(post_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設置請求方式
connection.setRequestMethod("POST");
//設置是否向遠程服務寫入數據
connection.setDoOutput(true);
//設置是否從遠程服務讀取數據
connection.setDoInput(true);
//設置是否使用緩存,post請求不能使用緩存
connection.setUseCaches(false);
//設置連接主機服務器超時時間
connection.setConnectTimeout(30000);
//設置讀取主機服務器返回數據超時時間
connection.setReadTimeout(30000);
//設置本次連接是否自動重定向
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
//設置接收數據的格式
connection.setRequestProperty("Accept", "application/json");
//設置請求參數的數據格式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//設置與服務器保持連接
connection.addRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;0.9");
//連接
connection.connect();
//獲取響應
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//post參數
String content = "name="+URLEncoder.encode("小明", "utf-8")+"&password=123";
out.writeBytes(content);
//out.write(content);
//響應碼
int responseCode = connection.getResponseCode();
//200
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuffer str = new StringBuffer();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
try{
String line = "";
while((line = br.readLine()) != null) {
str.append(line);
}
} finally {
br.close();
in.close();
}
JSONObject jsonObject = new JSONObject(str.toString());
result.put("code", jsonObject.get("code"));
result.put("message", jsonObject.get("message"));
}else{
result.put("code", responseCode);
result.put("message", "異常");
}
//關閉流
out.flush();
out.close();
//斷開連接
connection.disconnect();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}