Java Code Examples for javax.servlet.http.HttpServletRequest.getReader()

The following are Jave code examples for showing how to use getReader() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: JAVA-   File: WebUtil.java   View Source Code Vote up 8 votes
@SuppressWarnings("unchecked")
public static Map<String, Object> getParameter(HttpServletRequest request) {
	String str, wholeStr = "";
	try {
		BufferedReader br = request.getReader();
		while ((str = br.readLine()) != null) {
			wholeStr += str;
		}
		if (StringUtils.isNotBlank(wholeStr)) {
			return JSON.parseObject(wholeStr, Map.class);
		}
	} catch (Exception e) {
		logger.error("", e);
	}
	return getParameterMap(request);
}
 
Example 2
Project: tomcat7   File: TestInputBuffer.java   View Source Code Vote up 8 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    Reader r = req.getReader();

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");
    Writer w = resp.getWriter();

    try {
        // Copy one character at a time
        int c = r.read();
        while (c != -1) {
            w.write(c);
            c = r.read();
        }
        w.close();
    } catch (MalformedInputException mie) {
        resp.resetBuffer();
        w.write("FAILED");
    }
}
 
Example 3
Project: automat   File: WebUtil.java   View Source Code Vote up 7 votes
@SuppressWarnings("unchecked")
public static Map<String, Object> getParameter(HttpServletRequest request) {
	String str, wholeStr = "";
	try {
		BufferedReader br = request.getReader();
		while ((str = br.readLine()) != null) {
			wholeStr += str;
		}
		if (StringUtils.isNotBlank(wholeStr)) {
			return JSON.parseObject(wholeStr, Map.class);
		}
	} catch (Exception e) {
		logger.error("", e);
	}
	return getParameterMap(request);
}
 
Example 4
Project: springboot-shiro-cas-mybatis   File: SamlServiceFactory.java   View Source Code Vote up 6 votes
/**
 * Gets the request body from the request.
 *
 * @param request the request
 * @return the request body
 */
private String getRequestBody(final HttpServletRequest request) {
    final StringBuilder builder = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
        if (reader == null) {
            logger.debug("Request body could not be read because it's empty.");
            return null;
        }
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (final Exception e) {
        logger.trace("Could not obtain the saml request body from the http request", e);
        return null;
    }
}
 
Example 5
Project: replan_optimizer_v2   File: ReplanApiController.java   View Source Code Vote up 6 votes
private String requestContentAsString(HttpServletRequest request) {
    StringBuffer buffer = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            buffer.append(line);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return buffer.toString();
}
 
Example 6
Project: iBase4J-Common   File: WebUtil.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> List<T> getParameters(HttpServletRequest request, Class<T> cls) {
	String str, wholeStr = "";
	try {
		BufferedReader br = request.getReader();
		while ((str = br.readLine()) != null) {
			wholeStr += str;
		}
		if (StringUtils.isNotBlank(wholeStr)) {
			logger.info("request===>" + wholeStr);
			List list = JSON.parseObject(wholeStr, List.class);
			List<T> resultList = InstanceUtil.newArrayList();
			for (Object map : list) {
				T t = (T) InstanceUtil.transMap2Bean((Map) map, cls);
				resultList.add(t);
			}
			request.setAttribute("iBase4J.Parameters", resultList);
			return resultList;
		}
	} catch (Exception e) {
		logger.error("", e);
	}
	logger.info("request===>" + JSON.toJSONString(request.getParameterMap()));
	return Request2ListUtil.covert(cls, request);
}
 
Example 7
Project: neoscada   File: JsonServlet.java   View Source Code Vote up 6 votes
@Override
protected void doPost ( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException
{
    if ( request.getPathInfo () == null )
    {
        send404Error ( request, response );
        return;
    }
    if ( request.getPathInfo ().equals ( "/publish" ) || request.getPathInfo ().equals ( "/publish/" ) )
    {
        // read input
        final BufferedReader reader = request.getReader ();
        final char[] buffer = new char[4 * 1024];
        int len;
        final StringBuilder sb = new StringBuilder ();
        while ( ( len = reader.read ( buffer, 0, buffer.length ) ) != -1 )
        {
            sb.append ( buffer, 0, len );
        }
        final Event event = EventSerializer.deserializeEvent ( sb.toString () );

        this.injector.injectEvent ( event, new InjectionContext.Builder ().sourceModule ( "org.eclipse.scada.ae.server.http" ).build () );

        // return output
        response.setContentType ( "text/plain" );
        final PrintWriter pw = new PrintWriter ( response.getOutputStream () );
        pw.write ( "OK" );
        pw.close ();
    }
    else
    {
        send404Error ( request, response );
    }
}
 
Example 8
Project: cas-server-4.2.1   File: SamlServiceFactory.java   View Source Code Vote up 6 votes
/**
 * Gets the request body from the request.
 *
 * @param request the request
 * @return the request body
 */
private String getRequestBody(final HttpServletRequest request) {
    final StringBuilder builder = new StringBuilder();
    try (final BufferedReader reader = request.getReader()) {

        if (reader == null) {
            logger.debug("Request body could not be read because it's empty.");
            return null;
        }
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (final Exception e) {
        logger.trace("Could not obtain the saml request body from the http request", e);
        return null;
    }
}
 
Example 9
Project: hotelbook-JavaWeb   File: InsertLoginServlet.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("application/json; charset=utf-8");

    // 获取前端传递的json数据
    BufferedReader reader = request.getReader();
    String json = reader.readLine();

    // 解析json
    Gson gson = new Gson();
    Login login = gson.fromJson(json, Login.class);

    LoginService service = new LoginServiceImpl();
    int code = service.insertLogin(login);

    PrintWriter out = response.getWriter();
    out.print(gson.toJson(code));
}
 
Example 10
Project: cas-5.1.0   File: SamlServiceFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the request body from the request.
 *
 * @param request the request
 * @return the request body
 */
private static String getRequestBody(final HttpServletRequest request) {
    try(BufferedReader reader = request.getReader()) {
        if (reader == null) {
            LOGGER.debug("Request body could not be read because it's empty.");
            return null;
        }
        return reader.lines().collect(Collectors.joining());
    } catch (final Exception e) {
        LOGGER.trace("Could not obtain the saml request body from the http request", e);
        return null;
    }
}
 
Example 11
Project: allure-java   File: HttpServletAttachmentBuilder.java   View Source Code Vote up 5 votes
public static String getBody(final HttpServletRequest request) {
    final StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
        readBody(sb, reader);
    } catch (IOException e) {
        LOGGER.warn("Could not read request body", e);
    }
    return sb.toString();
}
 
Example 12
Project: automat   File: WebUtil.java   View Source Code Vote up 5 votes
public static <T> T getParameter(HttpServletRequest request, Class<T> cls) {
	String str, wholeStr = "";
	try {
		BufferedReader br = request.getReader();
		while ((str = br.readLine()) != null) {
			wholeStr += str;
		}
		if (StringUtils.isNotBlank(wholeStr)) {
			return JSON.parseObject(wholeStr, cls);
		}
	} catch (Exception e) {
		logger.error("", e);
	}
	return Request2ModelUtil.covert(cls, request);
}
 
Example 13
Project: Dude   File: DudeController.java   View Source Code Vote up 5 votes
private String _readJsonFromRequest(HttpServletRequest request) throws IOException {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader br = request.getReader()) {
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    }
    return sb.toString();
}
 
Example 14
Project: uavstack   File: SimpleServlet.java   View Source Code Vote up 5 votes
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    BufferedReader reader = req.getReader();
    String str, wholeStr = "";
    while ((str = reader.readLine()) != null) {
        wholeStr += str;
    }
    System.out.println(wholeStr);

    OutputStream outputStream = resp.getOutputStream();
    byte[] dataByteArr = wholeStr.getBytes("UTF-8");
    outputStream.write(dataByteArr);
}
 
Example 15
Project: lams   File: IMSPOXRequest.java   View Source Code Vote up 5 votes
public void loadFromRequest(HttpServletRequest request) 
{
	String contentType = request.getContentType();
	if ( ! "application/xml".equals(contentType) ) {
		errorMessage = "Content Type must be application/xml";
		Log.info(errorMessage+"\n"+contentType);
		return;
	}

	setAuthHeader(request.getHeader("Authorization"));
	if ( oauth_body_hash == null ) {
		errorMessage = "Did not find oauth_body_hash";
		Log.info(errorMessage+"\n"+header);
		return;
	}

	try {
		Reader in = request.getReader();
		postBody = readPostBody(in);
	} catch(Exception e) {
		errorMessage = "Could not read message body:"+e.getMessage();
		return;
	}

	validatePostBody();
	if (errorMessage != null) return;

	parsePostBody();
}
 
Example 16
Project: hotelbook-JavaWeb   File: InsertRoomTypeServlet.java   View Source Code Vote up 5 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");

        // 获取前端传递的json数据
        BufferedReader reader = request.getReader();
        String json = reader.readLine();

        // 解析json
        Gson gson = new Gson();
        RoomType roomType = gson.fromJson(json, RoomType.class);

        //主键ID没有想好暂时就用时间吧
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
        roomType.setTypeId("RT" + df.format(day));

        // 调用service
        RoomTypeService service = new RoomTypeServiceImpl();
        PrintWriter out = response.getWriter();

        int code = service.insertRoomType(roomType);

        //code 1:插入成功 0:存在同名项 -1:插入失败
        out.print(gson.toJson(code));
    }
 
Example 17
Project: autorest-streaming-example   File: Servlet.java   View Source Code Vote up 4 votes
public static String read(HttpServletRequest input) throws IOException {
    try (BufferedReader reader = input.getReader()) {
        return reader.lines().collect(Collectors.joining("\n"));
    }
}
 
Example 18
Project: x7   File: ServletModelCreator.java   View Source Code Vote up 4 votes
public static Map<String, Object> createMapBySimpleHttp(HttpServletRequest request) {

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String str = jb.toString();
		str = str.trim();

		System.out.println("createMapBySimpleHttp, str:  " + str);

		Map<String, Object> map = null;

		if (str.startsWith("{") && str.endsWith("}")) {

			str = str.replace("<", "&lt").replace(">", "&gt");

			map = JsonX.toMap(str);

			System.out.println("createMapBySimpleHttp, map:  " + map);

			return map;
		}

		map = new HashMap<String, Object>();

		if (str.contains("=")) {
			String[] arr = str.split("&");
			for (String kv : arr) {
				if (kv.contains("=")) {
					String[] kvArr = kv.split("=");
					String v = kvArr[1];
					v = v.replace("<", "&lt").replace(">", "&gt");
					map.put(kvArr[0], v);
				}
			}
		}

		System.out.println("createMapBySimpleHttp, map:  " + map);

		return map;
	}
 
Example 19
Project: Panako   File: MetaDataServlet.java   View Source Code Vote up 4 votes
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
	
	StringBuffer jb = new StringBuffer();
	String line = null;
	try {
		BufferedReader reader = request.getReader();
		while ((line = reader.readLine()) != null) {
			jb.append(line);
		}
	} catch (Exception e) {
		/* report an error */
	}
	
	String incomJSONRequest = jb.toString();
	
	System.out.println("recieved a MetaData JSON request");
	System.out.println("on thread:" + Thread.currentThread().getId());
	
	JSONObject obj = new JSONObject(incomJSONRequest);
	
	Integer identifier = Integer.parseInt(obj.get("id").toString());
	
	System.out.println("Fetch Metadata for:");
	System.out.println("Audio identifier: " + identifier);
	
	
	String fileName = strategy.getAudioDescription(identifier);
	

	final PrintWriter output = response.getWriter();
	if(fileName==null){
		output.println("{\"error\":\"No audio file with descriptor id " + identifier + " found.\"}");
	}else{
		fileName = identifier + ".mp3";
		String extension = "";
		int i = fileName.lastIndexOf('.');
		if (i > 0) {
		    extension = fileName.substring(i+1);
		}

		
		String jsonMetadataFile = new File(metaDataDirectory,fileName.replace(extension, "json")).getAbsolutePath();;
		if(FileUtils.exists(jsonMetadataFile)){
			output.println(FileUtils.readFile(jsonMetadataFile));
			// Set the response message's MIME type
			response.setContentType("application/json");
		}else{
			output.println("{\"error\":\"No JSON meta data file found at "+ jsonMetadataFile + ".\"}");
		}
	}
	
	
	
	// Allocate a output writer to write the response message into the
	// network socket
	output.close();
}
 
Example 20
Project: alfresco-remote-api   File: BaseAuthenticationFilter.java   View Source Code Vote up 4 votes
/**
 * Handles the login form directly, allowing management of the session user.
 * 
 * @param req
 *            the request
 * @param res
 *            the response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             on error
 */
protected boolean handleLoginForm(HttpServletRequest req, HttpServletResponse res) throws IOException,
        ServletException
{
    if (getLogger().isDebugEnabled())
        getLogger().debug("Handling the login form.");
    // Invalidate current session
    HttpSession session = req.getSession(false);
    if (session != null)
    {
        session.invalidate();
    }
    StringBuilder out = new StringBuilder(1024);
    Reader in = req.getReader();
    char[] buff = new char[1024];
    int charsRead;
    while ((charsRead = in.read(buff)) != -1)
    {
        out.append(buff, 0, charsRead);
    }
    in.close();

    try
    {
        JSONObject json = new JSONObject(out.toString());
        String username = json.getString("username");
        String password = json.getString("password");

        if (username == null || username.length() == 0)
        {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Username not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
            return false;
        }

        if (password == null)
        {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Password not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
            return false;
        }

        authenticationService.authenticate(username, password.toCharArray());
        session = req.getSession();            
        createUserEnvironment(session, username, authenticationService.getCurrentTicket(), false);
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return true;
    }
    catch (AuthenticationException e)
    {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login failed", e);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    }
    catch (JSONException jErr)
    {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Unable to parse JSON POST body", jErr);
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    return false;
}