版權聲明:本文首發 http://asing1elife.com ,轉載請注明出處。 https://blog.csdn.net/asing1elife/article/details/82788062
Java 通過 HttpConnection 解決 Ajax 請求跨域問題
$.ajax
在通路外部伺服器時會出現跨域問題,嘗試過很多前端的方式解決都沒有效果,最終是使用 Java 發送請求得以解決
更多精彩
- 更多技術部落格,請移步 asing1elife’s blog
包裝 Java 發送 Http 請求的工具類
- 該工具類中包括發送 GET/POST 請求的方法
- 方法隻需要傳入請求的位址和參數清單即可
- 參數清單的格式為
name1=value1&name2=value2
public class HttpUtils {
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接配接
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接配接
connection.connect();
// 擷取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接配接
URLConnection conn = realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設定如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 擷取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
} finally {
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
} catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
調用工具類
- 如果調用的是 GET 請求請求參數會被拼接到連結之後,這是參數清單則需要對各種符号進行轉碼
-
是 java.net.URLEncoder 包中的方法URLEncoder.encode(input, "UTF-8")
String result = sendGet("http://120.27.199.194:7001/run", "code=" + URLEncoder.encode(input, "UTF-8"));