Java Code Examples for javax.servlet.http.HttpServletRequest#getInputStream()
The following examples show how to use
javax.servlet.http.HttpServletRequest#getInputStream() .
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: MessageUtil.java From jeewx with Apache License 2.0 | 6 votes |
public static String readStrFromInputStream(HttpServletRequest request){ // 从request中取得输入流 StringBuffer sbf = new StringBuffer(); try { InputStream inputStream = request.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); char[] bufferChar = new char[1024]; int index = 0; while((index=in.read(bufferChar))!=-1){ sbf.append(bufferChar,0,index); } inputStream.close(); inputStream =null; return sbf.toString(); } catch (IOException e) { e.printStackTrace(); } return null; }
Example 2
Source File: LegacyApiTest.java From java-slack-sdk with MIT License | 6 votes |
private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException { try (InputStream is = req.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) { String requestBody = br.lines().collect(Collectors.joining()); log.info("request body: {}", requestBody); } String endpoint = req.getRequestURI().replaceFirst("^/api/", ""); String body = reader.readWholeAsString(endpoint + ".json"); body = body.replaceFirst("\"ok\": false,", "\"ok\": true,"); if (body == null || body.trim().isEmpty()) { resp.setStatus(400); return; } resp.setStatus(200); resp.getWriter().write(body); resp.setContentType("application/json"); }
Example 3
Source File: ApiTest.java From java-slack-sdk with MIT License | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try (InputStream is = req.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) { String requestBody = br.lines().collect(Collectors.joining()); log.info("request body: {}", requestBody); } String endpoint = req.getRequestURI().replaceFirst("^/api/", ""); String body = reader.readWholeAsString(endpoint + ".json"); body = body.replaceFirst("\"ok\": false,", "\"ok\": true,"); if (body == null || body.trim().isEmpty()) { resp.setStatus(400); return; } resp.setStatus(200); resp.getWriter().write(body); resp.setContentType("application/json"); }
Example 4
Source File: NumberWriter.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); // Non-blocking IO requires async AsyncContext ac = req.startAsync(); // Use a single listener for read and write. Listeners often need to // share state to coordinate reads and writes and this is much easier as // a single object. @SuppressWarnings("unused") NumberWriterListener listener = new NumberWriterListener( ac, req.getInputStream(), resp.getOutputStream()); }
Example 5
Source File: TestJobEndNotifier.java From hadoop with Apache License 2.0 | 6 votes |
@Override public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { InputStreamReader in = new InputStreamReader(request.getInputStream()); PrintStream out = new PrintStream(response.getOutputStream()); calledTimes++; try { requestUri = new URI(null, null, request.getRequestURI(), request.getQueryString(), null); } catch (URISyntaxException e) { } in.close(); out.close(); }
Example 6
Source File: WeiXinPaySupportUtil.java From springbootexamples with Apache License 2.0 | 6 votes |
/** * 从request的inputStream中获取参数 * code come from https://github.com/mengday/springboot-pay-example/blob/master/src/main/java/com/example/pay/configuration/WXPayClient.java * @param request * @return * @throws Exception */ public static Map<String, String> getNotifyParameter(HttpServletRequest request) throws Exception { InputStream inputStream = request.getInputStream(); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { outSteam.write(buffer, 0, length); } outSteam.close(); inputStream.close(); // 获取微信调用我们notify_url的返回信息 String resultXml = new String(outSteam.toByteArray(), "utf-8"); Map<String, String> notifyMap = WXPayUtil.xmlToMap(resultXml); return notifyMap; }
Example 7
Source File: MetricRestServlet.java From realtime-analytics with GNU General Public License v2.0 | 5 votes |
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletInputStream inputStream = request.getInputStream(); if (inputStream != null) { inputStream.mark(Integer.MAX_VALUE); } try { String pathInfo = request.getPathInfo(); if (pathInfo.startsWith(PATH_PING)) { ping(request, pathInfo, response); } else if (pathInfo.startsWith(PATH_COUNTER)) { stats.incQueryRequestCount(); getCounters(request, pathInfo, response); } else if (pathInfo.startsWith(PATH_METRICGROUP)) { stats.incQueryRequestCount(); getMetrics(request, pathInfo, response); } else { stats.incInvalidRequestCount(); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (Throwable ex) { String requestTxt = readRequest(request); stats.setLastFailedRequest(readRequestHead(request) + requestTxt); stats.registerError(ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); }finally{ response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "*"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); } }
Example 8
Source File: IoUtil.java From endpoints-java with Apache License 2.0 | 5 votes |
/** * Gets an uncompressed {@link InputStream} for the request. If the request specifies gzip * encoding, tries to wrap the request input stream in a {@link GZIPInputStream}. If the input * stream does not start with a gzip header, then a stream representing a plaintext request is * returned. */ public static InputStream getRequestInputStream(HttpServletRequest request) throws IOException { InputStream bodyStream = request.getInputStream(); if (bodyStream != null && GZIP_ENCODING.equals(request.getHeader(HEADER_CONTENT_ENCODING))) { PushbackInputStream pushbackStream = new PushbackInputStream(bodyStream, 2); byte[] header = new byte[2]; int len = pushbackStream.read(header); if (len > 0) { pushbackStream.unread(header, 0, len); } return isGzipHeader(header) ? new GZIPInputStream(pushbackStream) : pushbackStream; } return bodyStream; }
Example 9
Source File: ReceiveMessageServlet.java From cloud-pubsub-samples-java with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { // Validating unique subscription token before processing the message String subscriptionToken = System.getProperty( Constants.BASE_PACKAGE + ".subscriptionUniqueToken"); if (!subscriptionToken.equals(req.getParameter("token"))) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().close(); return; } ServletInputStream inputStream = req.getInputStream(); // Parse the JSON message to the POJO model class JsonParser parser = JacksonFactory.getDefaultInstance() .createJsonParser(inputStream); parser.skipToKey("message"); PubsubMessage message = parser.parseAndClose(PubsubMessage.class); // Store the message in the datastore Entity messageToStore = new Entity("PubsubMessage"); messageToStore.setProperty("message", new String(message.decodeData(), "UTF-8")); messageToStore.setProperty("receipt-time", System.currentTimeMillis()); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(messageToStore); // Invalidate the cache MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(); memcacheService.delete(Constants.MESSAGE_CACHE_KEY); // Acknowledge the message by returning a success code resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().close(); }
Example 10
Source File: BodyReaderHttpServletRequestWrapper.java From qconfig with MIT License | 5 votes |
public BodyReaderHttpServletRequestWrapper(final HttpServletRequest request) throws IOException { super(request); try (InputStream inputStream = request.getInputStream()) { body = ByteStreams.toByteArray(inputStream); } }
Example 11
Source File: PuzzleServlet.java From shortyz with GNU General Public License v3.0 | 5 votes |
public FakeRequest(HttpServletRequest request) throws IOException { super(request); InputStream is = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(is, baos); System.out.println(new String(baos.toByteArray())); this.bytes = baos.toByteArray(); }
Example 12
Source File: AbstractRequestHandler.java From secure-data-service with Apache License 2.0 | 5 votes |
protected String getRequestString(HttpServletRequest req) { String result = ""; InputStream xml = null; try { xml = req.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(xml, writer, "UTF-8"); result = writer.toString(); } catch (IOException e) { LOG.error("Exception reading request: ", e); } return result; }
Example 13
Source File: PrintRequestContentFilter.java From tutorials with MIT License | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { System.out.println("IN PrintRequestContentFilter "); InputStream inputStream = httpServletRequest.getInputStream(); byte[] body = StreamUtils.copyToByteArray(inputStream); System.out.println("In PrintRequestContentFilter. Request body is: " + new String(body)); filterChain.doFilter(httpServletRequest, httpServletResponse); }
Example 14
Source File: FidoServerAssertionResultEndpointFilter.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { InputStream inputStream; try { inputStream = request.getInputStream(); } catch (IOException e) { throw new UncheckedIOException(e); } ServerPublicKeyCredential<ServerAuthenticatorAssertionResponse> credential = jsonConverter.readValue(inputStream, credentialTypeRef); serverPublicKeyCredentialValidator.validate(credential); ServerAuthenticatorAssertionResponse assertionResponse = credential.getResponse(); ServerProperty serverProperty = serverPropertyProvider.provide(request); CollectedClientData collectedClientData = collectedClientDataConverter.convert(assertionResponse.getClientDataJSON()); UserVerificationRequirement userVerificationRequirement = serverEndpointFilterUtil.decodeUserVerification(collectedClientData.getChallenge()); WebAuthnAuthenticationRequest webAuthnAuthenticationRequest = new WebAuthnAuthenticationRequest( Base64UrlUtil.decode(credential.getRawId()), Base64UrlUtil.decode(assertionResponse.getClientDataJSON()), Base64UrlUtil.decode(assertionResponse.getAuthenticatorData()), Base64UrlUtil.decode(assertionResponse.getSignature()), credential.getClientExtensionResults(), serverProperty, userVerificationRequirement == UserVerificationRequirement.REQUIRED, false, expectedAuthenticationExtensionIds ); WebAuthnAssertionAuthenticationToken authRequest = new WebAuthnAssertionAuthenticationToken(webAuthnAuthenticationRequest); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
Example 15
Source File: ExampleController.java From logbook with MIT License | 5 votes |
@RequestMapping(path = "/read-byte", produces = TEXT_PLAIN_VALUE) public void readByte(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final ServletInputStream input = request.getInputStream(); final ServletOutputStream output = response.getOutputStream(); while (true) { final int read = input.read(); if (read == -1) { break; } output.write(read); } }
Example 16
Source File: EsRestServlet.java From uavstack with Apache License 2.0 | 5 votes |
@Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求资源 String proName = req.getServletContext().getContextPath(); String requestSource = req.getRequestURI(); requestSource = requestSource.substring(requestSource.indexOf(proName) + proName.length()); if (requestSource.startsWith("/es")) { requestSource = requestSource.substring(3); } /** * get url */ Map<String, ConnectionFailoverMgr> connectionMgrPool = EsResource.getConnMgr(); String forwarUrl = connectionMgrPool.get("es.info.forwar.url").getConnection() + requestSource; /** * get method */ String method = req.getMethod(); /** * get body */ ServletInputStream input = req.getInputStream(); EsResource.getHttpAsyncClient().doAsyncHttpMethodWithReqAsync(method, forwarUrl, null, input, null, null, "application/json", "utf-8", new EsRestServletCallBack(), req); }
Example 17
Source File: FidoServerAssertionOptionsEndpointFilter.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
@Override protected ServerResponse processRequest(HttpServletRequest request) { InputStream inputStream; try { inputStream = request.getInputStream(); } catch (IOException e) { throw new UncheckedIOException(e); } ServerPublicKeyCredentialGetOptionsRequest serverRequest = objectConverter.getJsonConverter().readValue(inputStream, ServerPublicKeyCredentialGetOptionsRequest.class); String username = serverRequest.getUsername(); Challenge challenge = serverEndpointFilterUtil.encodeUserVerification(new DefaultChallenge(), serverRequest.getUserVerification()); AssertionOptions options = optionsProvider.getAssertionOptions(request, username, challenge); List<ServerPublicKeyCredentialDescriptor> credentials = options.getCredentials().stream().map(ServerPublicKeyCredentialDescriptor::new).collect(Collectors.toList()); AuthenticationExtensionsClientInputs<AuthenticationExtensionClientInput<?>> authenticationExtensionsClientInputs; if (serverRequest.getExtensions() != null) { authenticationExtensionsClientInputs = serverRequest.getExtensions(); } else { authenticationExtensionsClientInputs = options.getAuthenticationExtensions(); } return new ServerPublicKeyCredentialGetOptionsResponse( Base64UrlUtil.encodeToString(options.getChallenge().getValue()), options.getAuthenticationTimeout(), options.getRpId(), credentials, serverRequest.getUserVerification(), authenticationExtensionsClientInputs); }
Example 18
Source File: SystemCommonController.java From base-framework with Apache License 2.0 | 4 votes |
/** * 修改用户头像C * * @param request HttpServletRequest * @throws IOException */ @ResponseBody @RequestMapping("/change-portrait") public Map<String, Object> changePortrait(HttpServletRequest request) throws IOException { //获取当前用户 User entity = SystemVariableUtils.getSessionVariable().getUser(); Map<String, Object> result = Maps.newHashMap(); //获取传进来的流 InputStream is = request.getInputStream(); //读取流内容到ByteArrayOutputStream中 ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); int ch; while ((ch = is.read()) != -1) { bytestream.write(ch); } bytestream.close(); File uploadDirectory = new File(fileUploadPath); //如果没有创建上传文件夹就创建文件夹 if (!uploadDirectory.exists() || !uploadDirectory.isDirectory()) { uploadDirectory.mkdirs(); } entity.setPortrait(fileUploadPath + entity.getId()); File portraitFile = new File(fileUploadPath + entity.getId()); //如果当前用户没有创建头像,就创建头像 if (!portraitFile.exists()) { portraitFile.createNewFile(); } //拷贝到指定路径里 FileUtils.writeByteArrayToFile(portraitFile, bytestream.toByteArray()); accountManager.updateUser(entity); SystemVariableUtils.getSessionVariable().setUser(entity); //设置状态值,让FaustCplus再次触发jsfunc的js函数 result.put("status","success"); return result; }
Example 19
Source File: BodyProcessorCreator.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
@Override public Object getValue(HttpServletRequest request) throws Exception { Object body = request.getAttribute(RestConst.BODY_PARAMETER); if (body != null) { return convertValue(body, targetType); } // edge support convert from form-data or x-www-form-urlencoded to json automatically String contentType = request.getContentType(); contentType = contentType == null ? "" : contentType.toLowerCase(Locale.US); if (contentType.startsWith(MediaType.MULTIPART_FORM_DATA) || contentType.startsWith(MediaType.APPLICATION_FORM_URLENCODED)) { return convertValue(request.getParameterMap(), targetType); } // for standard HttpServletRequest, getInputStream will never return null // but for mocked HttpServletRequest, maybe get a null // like org.apache.servicecomb.provider.springmvc.reference.ClientToHttpServletRequest InputStream inputStream = request.getInputStream(); if (inputStream == null) { return null; } if (!contentType.isEmpty() && !contentType.startsWith(MediaType.APPLICATION_JSON)) { // TODO: we should consider body encoding return IOUtils.toString(inputStream, StandardCharsets.UTF_8); } try { ObjectReader reader = serialViewClass != null ? RestObjectMapperFactory.getRestObjectMapper().readerWithView(serialViewClass) : RestObjectMapperFactory.getRestObjectMapper().reader(); if (decodeAsObject) { return reader.forType(OBJECT_TYPE).readValue(inputStream); } return reader.forType(targetType == null ? OBJECT_TYPE : targetType) .readValue(inputStream); } catch (MismatchedInputException e) { // there is no way to detect InputStream is empty, so have to catch the exception if (!isRequired && e.getMessage().contains("No content to map due to end-of-input")) { LOGGER.info("Empty content and required is false, taken as null"); return null; } throw e; } }
Example 20
Source File: AnnotationMethodHandlerExceptionResolver.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * 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; } }