当前位置 : 主页 > 编程语言 > c++ >

request获取json 数据

来源:互联网 收集:自由互联 发布时间:2021-06-30
第一种方式获取json数据 /** * 获取json 数据 * @param request * @return * @throws Exception */public static String getRequestJsonString(HttpServletRequest request) throws Exception { String submitMehtod = request.getMethod(); if
第一种方式获取json数据
/**
	 * 获取json 数据
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String getRequestJsonString(HttpServletRequest request) throws Exception {
		  String submitMehtod = request.getMethod(); 
		 if (submitMehtod.equals("GET")) {	           
				return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
	    } else {
		        return getRequestPostStr(request);
	    }
	}
	 
	public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }
	
	public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {
            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }
第二种方式
InputStream is = request.getInputStream();   //获取流
	StringBuffer req= new StringBuffer(2048);
	int i;
	byte[] buffer1 = new byte[2048];
	 try{    
		i = is.read(buffer1);
		}catch(IOException e) { 
			e.printStackTrace(); 
			i = -1;
		}
	 for(int j = 0; j < i; j++){ 
		 req.append((char) buffer1[j]);
		}
	String str = req.toString();   
	
###################################################


InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String bb = br.readLine();
System.out.print("llllllllllllllllll: " + bb);
网友评论