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

The following examples show how to use javax.servlet.http.HttpServletRequest#getReader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EchoServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  resp.addHeader("Content-Encoding", "application/json");

  Object responseBody;
  try {
    JsonReader jsonReader = new JsonReader(req.getReader());
    responseBody = new Gson().fromJson(jsonReader, Map.class);
  } catch (JsonParseException je) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    JsonObject error = new JsonObject();
    error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
    error.addProperty("message", "Body was not valid JSON.");
    responseBody = error;
  }

  new Gson().toJson(responseBody, resp.getWriter());
}
 
Example 2
Source File: RequestUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 提取收到的HttpServletRequest请求报文体消息
 * <p>
 *     该方法默认使用了UTF-8解析请求消息
 *     解析过程中发生异常时会抛出RuntimeException
 * </p>
 */
public static String extractHttpServletRequestBodyMessage(HttpServletRequest request){
    try{
        request.setCharacterEncoding("UTF-8");
    }catch(UnsupportedEncodingException e1){
        //ignore
    }
    StringBuilder sb = new StringBuilder();
    try(BufferedReader br = request.getReader()){
        for(String line; (line=br.readLine())!=null;){
            sb.append(line).append("\n");
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}
 
Example 3
Source File: MockFilterHandler.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 包装请求参数为json
 *
 * @param request 请求
 * @return requestJson
 */
@SneakyThrows
private String requestToJson(HttpServletRequest request) {
    JSONObject requestJsonObj = new JSONObject();
    // get all header
    Map<String, String> headerMap = ServletUtil.getHeaderMap(request);
    requestJsonObj.put("headers", headerMap);
    // get all param
    Map<String, String> paramMap = ServletUtil.getParamMap(request);
    requestJsonObj.put("params", paramMap);
    // body
    @Cleanup BufferedReader reader = request.getReader();
    String body = reader.lines().collect(Collectors.joining(System.lineSeparator()));
    requestJsonObj.put("body", body);
    return requestJsonObj.toString();
}
 
Example 4
Source File: TestInputBuffer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: HttpServletAttachmentBuilder.java    From allure-java with Apache License 2.0 5 votes vote down vote up
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 6
Source File: RequestHandler.java    From vk-java-sdk with MIT License 5 votes vote down vote up
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        throw new ServletException("This method is unsupported");
    }

    Reader reader = request.getReader();

    try {
        JsonObject requestJson = gson.fromJson(reader, JsonObject.class);

        String type = requestJson.get("type").getAsString();

        if (type == null || type.isEmpty()) throw new ServletException("No type in json");

        final String responseBody;
        switch (type) {
            case CONFIRMATION_TYPE:
                responseBody = confirmationCode;
                break;
            case MESSAGE_TYPE:
                JsonObject object = requestJson.getAsJsonObject("object");
                int userId = object.getAsJsonPrimitive("user_id").getAsInt();
                botRequestHandler.handle(userId);
                responseBody = OK_BODY;
                break;
            default:
                responseBody = OK_BODY; // in case we get another event
                break;
        }

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println(responseBody);
    } catch (JsonParseException e) {
        throw new ServletException("Incorrect json", e);
    }
}
 
Example 7
Source File: JettyHttpServer.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
public void handle(String pathInContext, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {

        boolean validRequest;
        boolean validLogMessage = false;
        BufferedReader reader = httpRequest.getReader();
        StringBuilder logMessage = new StringBuilder();
        String line;

        if (httpRequest.getMethod().equals("POST")) {

            validRequest = isValidRequest(request);

            do {
                line = reader.readLine();

                if (line != null)
                    logMessage.append(line);
            }
            while (line != null);

            log.info("Log Message: ");
            log.info(logMessage);

            if (logMessage.toString().contains("@logstream"))
                validLogMessage = true;


            httpResponse.setContentType("application/json");
            if (validRequest && validLogMessage)
                httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
            else {
                httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            }

            request.setHandled(true);
        }
    }
 
Example 8
Source File: InlineHttpTransport.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String readBody(HttpServletRequest request) {
	try {
		BufferedReader reader = request.getReader();
		String line = null;
		StringBuilder lines = new StringBuilder();
		while((line = reader.readLine()) != null) {
			lines.append(line);
		}
		return lines.toString();
	} catch (IOException e) {
		throw new IllegalStateException();
	}
}
 
Example 9
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
private GitLabHookEvent parseEvent(@NotNull HttpServletRequest req) {
  try (final Reader reader = req.getReader()) {
    return GitLabHookEvent.parseEvent(reader);
  } catch (IOException e) {
    log.warn("Can't read hook data", e);
    return null;
  }
}
 
Example 10
Source File: AbstractRobot.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given HTTP request's input stream into a string.
 *
 * @param req the HTTP request to be read.
 * @return a string representation of the given HTTP request's body.
 *
 * @throws IOException if there is a problem reading the body.
 */
private static String readRequestBody(HttpServletRequest req) throws IOException {
  StringBuilder json = new StringBuilder();
  BufferedReader reader = req.getReader();
  String line;
  while ((line = reader.readLine()) != null) {
    json.append(line);
  }
  return json.toString();
}
 
Example 11
Source File: AbstractDataServlet.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
protected Object readBody(HttpServletRequest request) throws IOException {
    if (request.getReader() == null) return new DataSet();
    String body = IOUtils.toString(request.getReader()).trim();
    ObjectMapper objectMapper = JsonUtil.getMapper();
    if (body.startsWith("[")) {
        return objectMapper.<List<DataSet>>readValue(body,
                objectMapper.getTypeFactory().constructCollectionType(List.class, DataSet.class)
        );
    } else {
        return objectMapper.readValue(body, DataSet.class);
    }
}
 
Example 12
Source File: AbstractRobot.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given HTTP request's input stream into a string.
 *
 * @param req the HTTP request to be read.
 * @return a string representation of the given HTTP request's body.
 *
 * @throws IOException if there is a problem reading the body.
 */
private static String readRequestBody(HttpServletRequest req) throws IOException {
  StringBuilder json = new StringBuilder();
  BufferedReader reader = req.getReader();
  String line;
  while ((line = reader.readLine()) != null) {
    json.append(line);
  }
  return json.toString();
}
 
Example 13
Source File: GeoDynamoDBServlet.java    From dynamodb-geo with Apache License 2.0 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
		IOException {
	try {
		StringBuffer buffer = new StringBuffer();
		String line = null;
		BufferedReader reader = request.getReader();

		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}

		JSONObject jsonObject = new JSONObject(buffer.toString());
		PrintWriter out = response.getWriter();

		String action = jsonObject.getString("action");
		log("action: " + action);
		JSONObject requestObject = jsonObject.getJSONObject("request");
		log("requestObject: " + requestObject);

		if (action.equalsIgnoreCase("put-point")) {
			putPoint(requestObject, out);
		} else if (action.equalsIgnoreCase("get-point")) {
			getPoint(requestObject, out);
		} else if (action.equalsIgnoreCase("update-point")) {
			updatePoint(requestObject, out);
		} else if (action.equalsIgnoreCase("query-rectangle")) {
			queryRectangle(requestObject, out);
		} else if (action.equalsIgnoreCase("query-radius")) {
			queryRadius(requestObject, out);
		} else if (action.equalsIgnoreCase("delete-point")) {
			deletePoint(requestObject, out);
		}
	} catch (Exception e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		log(sw.toString());
	}
}
 
Example 14
Source File: PayController.java    From java_server with MIT License 5 votes vote down vote up
@RequestMapping("/webHooksForPayAndRefund")
public void webHooksForPaySuccess(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException, InvalidRequestException, APIConnectionException, APIException, ChannelException {
    request.setCharacterEncoding("UTF8");

    //获取头部所有信息
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        System.out.println(key + " " + value);
    }
    // 获得 http body 内容
    BufferedReader reader = request.getReader();
    StringBuffer buffer = new StringBuffer();
    String string;
    while ((string = reader.readLine()) != null) {
        buffer.append(string);
    }
    reader.close();
    // 解析异步通知数据
    Event event = Webhooks.eventParse(buffer.toString());
    if ("charge.succeeded".equals(event.getType())) {       //支付成功的回调
        doPaySuccess(buffer.toString());      //事务处理
        response.setStatus(200);
    } else if ("refund.succeeded".equals(event.getType())) {  //退款的回调
        doRefundSuccess(buffer.toString());       //退款事务处理
        response.setStatus(200);
    } else {
        response.setStatus(500);
    }
}
 
Example 15
Source File: HttpRequestHelper.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the request body payload.
 */
public static String getRequestBody(HttpServletRequest req) {
    try (BufferedReader br = req.getReader()) {
        return br.lines().collect(Collectors.joining(System.lineSeparator()));
    } catch (IOException e) {
        return "";
    }
}
 
Example 16
Source File: JsonServlet.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@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 17
Source File: RegisterBeamMetrics.java    From kettle-beam with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  if (isJettyMode() && !request.getRequestURI().startsWith(CONTEXT_PATH))
    return;

  if (log.isDebug()) {
    logDebug("Registration of Apache Beam Metrics");
  }

  // The Object ID
  //
  String carteObjectId = request.getParameter("id"); // the carte object id

  // Transformation name
  //
  String trans = request.getParameter("trans"); // the name of the transformation

  // Internal Job ID
  //
  String internalJobId = request.getParameter("internalJobId"); // the Id of the Spark/Flink job

  // Update date
  //
  Date updateDate = new Date();

  PrintWriter out = response.getWriter();
  BufferedReader in = request.getReader();
  
  WebResult webResult = new WebResult(WebResult.STRING_OK, "registration success", "");
  
  try {
    
    // First read the complete SlaveServerTransStatus object XML in memory from the request
    //
    StringBuilder xml = new StringBuilder(request.getContentLength());
    int c;
    while ((c = in.read()) != -1) {
      xml.append((char) c);
    }
    
    SlaveServerTransStatus transStatus = SlaveServerTransStatus.fromXML(xml.toString());
    
    MetricsRegistrationQueue registry = MetricsRegistrationQueue.getInstance();
    BeamMetricsEntry entry = new BeamMetricsEntry(carteObjectId, trans, internalJobId, updateDate, transStatus);
    registry.addNodeRegistryEntry(entry);
    
    response.setContentType("text/xml");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setCharacterEncoding(Const.XML_ENCODING);
    out.println(XMLHandler.getXMLHeader());
  } catch(Exception e) {
    webResult.setResult(WebResult.STRING_ERROR);
    webResult.setMessage(Const.getStackTracker(e));
  }
  out.println(webResult.getXML());
}
 
Example 18
Source File: ServletRequestMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	Class<?> paramType = parameter.getParameterType();
	if (WebRequest.class.isAssignableFrom(paramType)) {
		return webRequest;
	}

	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	if (ServletRequest.class.isAssignableFrom(paramType) || MultipartRequest.class.isAssignableFrom(paramType)) {
		Object nativeRequest = webRequest.getNativeRequest(paramType);
		if (nativeRequest == null) {
			throw new IllegalStateException(
					"Current request is not of type [" + paramType.getName() + "]: " + request);
		}
		return nativeRequest;
	}
	else if (HttpSession.class.isAssignableFrom(paramType)) {
		return request.getSession();
	}
	else if (HttpMethod.class == paramType) {
		return ((ServletWebRequest) webRequest).getHttpMethod();
	}
	else if (Principal.class.isAssignableFrom(paramType)) {
		return request.getUserPrincipal();
	}
	else if (Locale.class == paramType) {
		return RequestContextUtils.getLocale(request);
	}
	else if (TimeZone.class == paramType) {
		TimeZone timeZone = RequestContextUtils.getTimeZone(request);
		return (timeZone != null ? timeZone : TimeZone.getDefault());
	}
	else if ("java.time.ZoneId".equals(paramType.getName())) {
		return ZoneIdResolver.resolveZoneId(request);
	}
	else if (InputStream.class.isAssignableFrom(paramType)) {
		return request.getInputStream();
	}
	else if (Reader.class.isAssignableFrom(paramType)) {
		return request.getReader();
	}
	else {
		// should never happen...
		throw new UnsupportedOperationException(
				"Unknown parameter type: " + paramType + " in method: " + parameter.getMethod());
	}
}
 
Example 19
Source File: AnnotationMethodHandlerExceptionResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest},
 * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal},
 * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream},
 * response {@link Writer}, and the given {@code thrownException}.
 * @param parameterType the method parameter type
 * @param webRequest the request
 * @param thrownException the exception thrown
 * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED}
 */
protected Object resolveStandardArgument(Class<?> parameterType, NativeWebRequest webRequest,
		Exception thrownException) throws Exception {

	if (parameterType.isInstance(thrownException)) {
		return thrownException;
	}
	else if (WebRequest.class.isAssignableFrom(parameterType)) {
		return webRequest;
	}

	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

	if (ServletRequest.class.isAssignableFrom(parameterType)) {
		return request;
	}
	else if (ServletResponse.class.isAssignableFrom(parameterType)) {
		return response;
	}
	else if (HttpSession.class.isAssignableFrom(parameterType)) {
		return request.getSession();
	}
	else if (Principal.class.isAssignableFrom(parameterType)) {
		return request.getUserPrincipal();
	}
	else if (Locale.class == parameterType) {
		return RequestContextUtils.getLocale(request);
	}
	else if (InputStream.class.isAssignableFrom(parameterType)) {
		return request.getInputStream();
	}
	else if (Reader.class.isAssignableFrom(parameterType)) {
		return request.getReader();
	}
	else if (OutputStream.class.isAssignableFrom(parameterType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(parameterType)) {
		return response.getWriter();
	}
	else {
		return WebArgumentResolver.UNRESOLVED;

	}
}
 
Example 20
Source File: EventServlet.java    From kafka-connect-splunk with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  log.trace("Reading message body.");

  response.setHeader("X-Content-Type-Options", "nosniff");
  response.setHeader("X-Frame-Options", "SAMEORIGIN");
  response.setCharacterEncoding("UTF-8");
  response.setContentType(Json.MEDIA_TYPE);

  String remoteHost = host(request);

  try {

    try (BufferedReader bodyReader = request.getReader()) {
      try (EventIterator iterator = EventIterator.create(this.jsonFactory, bodyReader)) {

        while (iterator.hasNext()) {
          JsonNode jsonNode = iterator.next();

          if (log.isDebugEnabled()) {
            log.debug("Message received {}", jsonNode);
          }

          if (!this.allowedIndexes.isEmpty() && jsonNode.has("index")) {
            JsonNode indexNode = jsonNode.get("index");
            String index = indexNode.asText();

            if (!allowedIndexes.contains(index)) {

            }
          }

          SourceRecord sourceRecord = this.converter.convert(jsonNode, remoteHost);
          this.recordQueue.push(sourceRecord);
        }
      }
    }
    response.setStatus(200);

  } catch (Exception ex) {
    log.error("Exception thrown", ex);
    response.setStatus(500);
  }
}