1. 程式人生 > >(Java)使用Java傳送帶引數的http(GET)請求,獲取json資料

(Java)使用Java傳送帶引數的http(GET)請求,獲取json資料

	public String getCustomerInfo(Map<String, Object> map)
	{
    	String appId = (String)map.get("appId");
    	String name = (String)map.get("name");
    	JSONObject jsonObject = null;
    	OutputStreamWriter out = null;
        StringBuffer buffer = new StringBuffer();
        try {
	    //1.連線部分
            URL url = new URL("https://a.abc.com");
            // http協議傳輸
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 設定請求方式(GET/POST)
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.setRequestProperty("content-type", "application/x-www-form-urlencoded");  
			
	    //2.傳入引數部分
            // 得到請求的輸出流物件  
            out = new OutputStreamWriter(httpUrlConn.getOutputStream(),"UTF-8");  
            // 把資料寫入請求的Body
            out.write("appId=" + appId + "&name=" + name); //引數形式跟在位址列的一樣
            out.flush();  
            out.close(); 
            
	    //3.獲取資料
            // 將返回的輸入流轉換成字串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 釋放資源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
	}