1. 程式人生 > >java後臺發送請求並獲取返回值

java後臺發送請求並獲取返回值

otto wid eight quest 所有 ica 輸出流 lds thead

項目中需要前端發送請求給後端,而後端需要從另一個平臺中取數據然後再透傳給前端,通過下述代碼將其實現.在此記錄一下.

package com.autotest.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class BackEndHttpRequest{
	/**
	 * 向指定的URL發送GET方法的請求
	 * @param url    發送請求的URL
	 * @param param  請求參數,請求參數應該是 name1=value1&name2=value2 的形式 
	 * @return       遠程資源的響應結果 
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader bufferedReader = null;
		try {
			//1、讀取初始URL
			String urlNameString = url + "?
" + param;
			//2、將url轉變為URL類對象
			URL realUrl = new URL(urlNameString);
			
			//3、打開和URL之間的連接
			URLConnection connection = realUrl.openConnection();
			//4、設置通用的請求屬性
			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.setRequestProperty("Content-Type", "application/json; charset=utf-8");
			
			//5、建立實際的連接 
			connection.connect();
			//獲取所有響應頭字段
			Map<String, List<String>> map = connection.getHeaderFields();
			//遍歷所有的響應頭字段
			for(String key : map.keySet()) {
				System.out.println(key + "---->" + map.get(key));
			}
			
			//6、定義BufferedReader輸入流來讀取URL的響應內容 ,UTF-8是後續自己加的設置編碼格式,也可以去掉這個參數
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line = "";
			while(null != (line = bufferedReader.readLine())) {
				result += line;
			}
//			int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }
			
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println("發送GET請求出現異常!!!"  + e);
			e.printStackTrace();
		}finally {        //使用finally塊來關閉輸入流 
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			}catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 向指定的URL發送POST方法的請求
	 * @param url    發送請求的URL
	 * @param param  請求參數,請求參數應該是 name1=value1&name2=value2 的形式 
	 * @return       遠程資源的響應結果 
	 */
	public static String sendPost(String url, String param) {
		String result = "";
		BufferedReader bufferedReader = null;
		PrintWriter out = null;
		try {
			//1、2、讀取並將url轉變為URL類對象
			URL realUrl = new URL(url);
			
			//3、打開和URL之間的連接
			URLConnection connection = realUrl.openConnection();
			//4、設置通用的請求屬性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		
			// 發送POST請求必須設置如下兩行  
			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			//5、建立實際的連接
			//connection.connect();
			//獲取URLConnection對象對應的輸出流
			out = new PrintWriter(connection.getOutputStream());
			//發送請求參數
			out.print(param);
			//flush輸出流的緩沖
			out.flush();
			//
			
			//6、定義BufferedReader輸入流來讀取URL的響應內容
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			String line;
			while(null != (line = bufferedReader.readLine())) {
				result += line;
			}
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println("發送POST請求出現異常!!!"  + e);
			e.printStackTrace();
		}finally {        //使用finally塊來關閉輸出流、輸入流 
			try {
				if(null != out) {
					out.close();
				}
				if(null != bufferedReader) {
					bufferedReader.close();
				}
			}catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
	}
}

調用方法:

    public static void main(String[] args) {
        //發送 GET 請求
        String str1=BackEndHttpRequest.sendGet("http://localhost/services/getallcase/", "key=123&v=456");
        System.out.println(str1);
        
        //發送 POST 請求
        String str2=BackEndHttpRequest.sendPost("http://localhost/services/getallcase/", "key=123&v=456");
        System.out.println(str2);
    }

java後臺發送請求並獲取返回值