java通過http的request獲取請求參數

說明:今天調研某騰的某產品,通過對方的文檔知道可以在對方雲平臺設置回調地址,但文檔裏只有一張json格式的參數圖,我沒法知道對方會以怎樣的方式推過來,已經採用了字符串、對象、request.getParameter("")都不能正常獲取到參數,直到找到這個針對Http取值有點萬能的方法,這裏記錄下。

/**
	 * 讀取request中傳過來的字符串
	 * 有些調用方不知道用什麼方式調用,可能是【application/x-www-form-urlencoded】、【text/plain】、【application/json】
	 * 該方法都能處理,但是如果是按【application/x-www-form-urlencoded】
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private Map<String,Object> getDataFromRequest(HttpServletRequest request){
		Gson gson = new Gson();
		String type = request.getContentType();
		Map<String,Object> receiveMap = new HashMap<String,Object>();
		if("application/x-www-form-urlencoded".equals(type)){
			Enumeration<String> enu = request.getParameterNames();
			while (enu.hasMoreElements()) {
				String key = String.valueOf(enu.nextElement());
				String value = request.getParameter(key);
				receiveMap.put(key, value);
			}
		}else{	//else是text/plain、application/json這兩種情況
			BufferedReader reader = null;
	        StringBuilder sb = new StringBuilder();
	        try{
	            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
	            String line = null;
	            while ((line = reader.readLine()) != null){
	                sb.append(line);
	            }
	        } catch (IOException e){
	            e.printStackTrace();
	        } finally {
	            try{
	                if (null != reader){
	                	reader.close();
	                }
	            } catch (IOException e){
	            	e.printStackTrace();
	            }
	        }
	        receiveMap = gson.fromJson(sb.toString(), new TypeToken<Map<String, String>>(){}.getType());//把JSON字符串轉爲對象
		}
		return receiveMap;
	}

各位如果還在爲Http傳輸類型的接口取值方式苦惱,強烈建議採用上述代碼片段試試。

原文鏈接:https://blog.csdn.net/u011321514/article/details/89326677

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章