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

The following are Jave code examples for showing how to use getInputStream() 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: tulingchat   File: MessageUtil.java   View Source Code Vote up 7 votes
/**
 * @param @param request
 * @param @throws Exception
 * @Description: 解析微信发来的请求(XML)
 */
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
  // 将解析结果存储在 HashMap 中
  Map<String, String> map = new HashMap<String, String>();

  // 从 request 中取得输入流
  InputStream inputStream = request.getInputStream();
  // 读取输入流
  SAXReader reader = new SAXReader();
  Document document = reader.read(inputStream);
  // 得到 xml 根元素
  Element root = document.getRootElement();
  // 得到根元素的所有子节点
  List<Element> elementList = root.elements();

  // 遍历所有子节点
  for (Element e : elementList) {
    map.put(e.getName(), e.getText());
  }

  // 释放资源
  inputStream.close();
  inputStream = null;

  return map;
}
 
Example 2
Project: payment-wechat   File: WechatWebDemo.java   View Source Code Vote up 7 votes
/***
 * 需提供外部访问地址
 * 此处可以是SpringMVC、Struts2、Servlet 请根据项目前端框架编写如下代码.
 * 调用微信统一下单时,传入 UnifiedOrderInput.notify_url,应为该放方法的访问路径
 */
public void notify_wechat_pay(HttpServletRequest request, HttpServletResponse response){

    String status="SUCCESS",msg = "处理成功";
    PrintWriter writer = null;
    try {
        writer = response.getWriter();
        StringBuffer xmlResult = new StringBuffer();
        InputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String buffer = null;
        while ((buffer = br.readLine()) != null){
            xmlResult.append(buffer);
        }
        log.info("微信异步返回信息:"+ ThlwsBeanUtil.formatXml(xmlResult.toString()));
        NotifyOutput notifyOutput = WechatUtil.parseNotifyMsg(xmlResult.toString());
        //notifyOutput 是微信推送数据转换为Java对象,直接从该对象取值并进行相关业务操作
        //TODO 业务逻辑
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        writer.println("<xml><return_code><![CDATA["+status+"]]></return_code><return_msg><![CDATA["+msg+"]]></return_msg></xml>");
    }
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: BodyProcessorCreator.java   View Source Code Vote up 6 votes
@Override
public Object getValue(HttpServletRequest request) throws Exception {
  Object body = request.getAttribute(RestConst.BODY_PARAMETER);
  if (body != null) {
    return convertValue(body, 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;
  }

  String contentType = request.getContentType();
  if (contentType != null && !contentType.toLowerCase(Locale.US).startsWith(MediaType.APPLICATION_JSON)) {
    // TODO: we should consider body encoding
    return IOUtils.toString(inputStream, "UTF-8");
  }
  return RestObjectMapper.INSTANCE.readValue(inputStream, targetType);
}
 
Example 4
Project: S3Mock   File: FileStoreController.java   View Source Code Vote up 6 votes
/**
 * Adds an object to a bucket.
 *
 * http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
 *
 * @param bucketName the Bucket in which to store the file in.
 * @param request http servlet request
 * @return ResponseEntity with Status Code and ETag
 */
@RequestMapping(value = "/{bucketName:.+}/**", method = RequestMethod.PUT)
public ResponseEntity<String> putObject(@PathVariable final String bucketName,
    final HttpServletRequest request) {
  final String filename = filenameFrom(bucketName, request);
  try (ServletInputStream inputStream = request.getInputStream()) {
    final S3Object s3Object = fileStore.putS3Object(bucketName,
        filename,
        request.getContentType(),
        inputStream,
        isV4SigningEnabled(request));

    final HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setETag("\"" + s3Object.getMd5() + "\"");
    responseHeaders.setLastModified(s3Object.getLastModified());
    return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED);
  } catch (final IOException e) {
    LOG.error("Object could not be saved!", e);
    return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
 
Example 5
Project: parabuild-ci   File: StatelessTest.java   View Source Code Vote up 6 votes
/**
 * Returns a resource object as a result of a get request.
 **/
protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
    int length = req.getIntHeader( "Content-length" );
    String contentType = req.getHeader( "Content-type" );
    resp.setContentType( contentType );

    InputStreamReader isr = new InputStreamReader( req.getInputStream() );
    BufferedReader br = new BufferedReader( isr );
    resp.getWriter().print( length );

    String line = br.readLine();
    while (line != null) {
        resp.getWriter().print( "\n" );
        resp.getWriter().print( line );
        line = br.readLine();
    }
    resp.getWriter().flush();
    resp.getWriter().close();
}
 
Example 6
Project: apache-tomcat-7.0.73-with-comment   File: TesterSupport.java   View Source Code Vote up 6 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Swallow any request body
    int read = 0;
    int len = 0;
    byte[] buffer = new byte[4096];
    InputStream is = req.getInputStream();
    boolean contentOK = true;
    while (len > -1) {
        len = is.read(buffer);
        read = read + len;
        for (int i=0; i<len && contentOK; i++) {
            contentOK = (buffer[i] == DATA);
        }
    }
    // len will have been -1 on last iteration
    read++;

    // Report the number of bytes read
    resp.setContentType("text/plain");
    if (contentOK)
        resp.getWriter().print("OK-" + read);
    else
        resp.getWriter().print("CONTENT-MISMATCH-" + read);
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: ChatServlet.java   View Source Code Vote up 6 votes
protected void read(CometEvent event, HttpServletRequest request, HttpServletResponse response)
    throws IOException {
    InputStream is = request.getInputStream();
    byte[] buf = new byte[512];
    while (is.available() > 0) {
        log("Available: " + is.available());
        int n = is.read(buf);
        if (n > 0) {
            log("Read " + n + " bytes: " + new String(buf, 0, n)
                    + " for session: " + request.getSession(true).getId());
        } else if (n < 0) {
            log("End of file: " + n);
            end(event, request, response);
            return;
        }
    }
}
 
Example 8
Project: validator-web   File: GsonHttpMessageReader.java   View Source Code Vote up 5 votes
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpServletRequest request)
        throws IOException, HttpMessageNotReadableException {
    
    InputStream in = request.getInputStream();
    return gson.fromJson(new InputStreamReader(in), clazz);
}
 
Example 9
Project: eventapis   File: RequestResponseDumpFilter.java   View Source Code Vote up 5 votes
public BufferedRequestWrapper(HttpServletRequest req) throws IOException {
    super(req);
    // Read InputStream and store its content in a buffer.
    InputStream is = req.getInputStream();
    this.baos = new ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int letti;
    while ((letti = is.read(buf)) > 0) {
        this.baos.write(buf, 0, letti);
    }
    this.buffer = this.baos.toByteArray();
}
 
Example 10
Project: gerrit-plugin   File: GerritWebHook.java   View Source Code Vote up 5 votes
private GerritProjectEvent getBody(HttpServletRequest req) throws IOException {
  char[] body = new char[req.getContentLength()];
  try (InputStreamReader is = new InputStreamReader(req.getInputStream())) {
    IOUtils.readFully(is, body);
    String bodyString = new String(body);
    log.info("Received body: " + bodyString);
    return gson.fromJson(bodyString, GerritProjectEvent.class);
  }
}
 
Example 11
Project: oscm   File: PSPResponse.java   View Source Code Vote up 5 votes
/**
 * Converts the input given in the request to a properties object.
 * 
 * @param request
 *            The received request.
 * @return The properties contained in the request.
 * @throws IOException
 *             Thrown in case the request information could not be
 *             evaluated.
 */
private boolean determinePSPParams(HttpServletRequest request, Properties p) {
    

    try {
        ServletInputStream inputStream = request.getInputStream();
        if (inputStream == null) {
            return false;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                inputStream, "UTF-8"));
        String line = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        String params = sb.toString();
        StringTokenizer st = new StringTokenizer(params, "&");
        while (st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            String[] splitResult = nextToken.split("=");
            String key = splitResult[0];
            String value = "";
            if (splitResult.length > 1) {
                value = URLDecoder.decode(splitResult[1], "UTF-8");
            }
            p.setProperty(key, value);
        }
        return validateResponse(p);
    } catch (IOException e) {
        // if the request information cannot be read, we cannot determine
        // whether the registration worked or not. Hence we assume it
        // failed, log a warning and return the failure-URL to the PSP.
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_HEIDELPAY_INPUT_PROCESS_FAILED);
    }
    
    return false;
}
 
Example 12
Project: framework   File: ThriftServiceExporter.java   View Source Code Vote up 5 votes
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[]{"POST"}, "ThriftServiceExporter only supports POST requests");
	}

	InputStream in = request.getInputStream();
	OutputStream out = response.getOutputStream();
	try {
		ThriftContextHolder.init();
		response.setContentType("application/x-thrift");
		TTransport transport = new TIOStreamTransport(in, out);

		TProtocol protocol = getProtocolFactory().getProtocol(transport);
		TProcessor processor = ThriftUtil.buildProcessor(getServiceInterface(), getProxyForService());
		processor.process(protocol, protocol);
	} catch (Throwable e) {
		response.setContentType("text/plain; charset=UTF-8");
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		e.printStackTrace(new PrintWriter(out, true));
		if (LOGGER.isErrorEnabled()) {
			LOGGER.error("Thrift server direct error", e);
		}
	} finally {
		ThriftContextHolder.reset();
	}
}
 
Example 13
Project: jwx   File: WeixinDispatcherServlet.java   View Source Code Vote up 5 votes
/**
 * 读取post请求原始xml内容
 * 
 * @param request
 * @return
 * @throws IOException
 */
private String getRequestOriginalXml(HttpServletRequest request) throws IOException {
	BufferedReader in = new BufferedReader(
			new InputStreamReader(request.getInputStream(), Charset.forName("UTF-8")));
	StringBuilder sb = new StringBuilder();
	String line = null;
	while ((line = in.readLine()) != null) {
		sb.append(line);

	}
	return sb.toString();
}
 
Example 14
Project: Equella   File: WebdavServlet.java   View Source Code Vote up 5 votes
/**
 * Handles the PUT method, which uploads a file to the server.
 * 
 * @param req HTTP Request from client
 * @param resp HTTP Response to client
 */
public void putMethod(HttpServletRequest req, HttpServletResponse resp, StagingFile staging, String filename)
	throws IOException
{
	try( InputStream in = req.getInputStream() )
	{
		fileSystemService.write(staging, filename, in, false);
		resp.setStatus(HttpServletResponse.SC_CREATED);
	}
}
 
Example 15
Project: validator-web   File: AbstractJackson2HttpMessageReader.java   View Source Code Vote up 5 votes
private Object readJavaType(JavaType javaType, HttpServletRequest request) {
    try {
        InputStream in = request.getInputStream();
        return this.objectMapper.readValue(in, javaType);
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
 
Example 16
Project: theskeleton   File: ProfileRestController.java   View Source Code Vote up 5 votes
@PutMapping(path = "/picture", consumes = "image/*")
public ProfileRestData updateProfilePicture(Authentication authentication, HttpServletRequest request) throws Exception {
	try (InputStream image = request.getInputStream()) {
		UserEntity user = profileService.updateProfilePicture(authentication.getName(), image, request.getContentType());
		return convertToRestData(user);
	}
}
 
Example 17
Project: lams   File: AbstractRequestLoggingFilter.java   View Source Code Vote up 4 votes
private RequestCachingRequestWrapper(HttpServletRequest request) throws IOException {
	super(request);
	this.inputStream = new RequestCachingInputStream(request.getInputStream());
}
 
Example 18
Project: ditb   File: GZIPRequestStream.java   View Source Code Vote up 4 votes
public GZIPRequestStream(HttpServletRequest request) throws IOException {
  this.in = new GZIPInputStream(request.getInputStream());
}
 
Example 19
Project: oscm   File: SsoHttpServletRequestWrapper.java   View Source Code Vote up 4 votes
public SsoHttpServletRequestWrapper(HttpServletRequest request) {
    super(request);
    try {
        servletInputStream = request.getInputStream();
        if (servletInputStream != null
                && !servletInputStream.markSupported()) {
            servletInputStream = new BufferedServletInputStream(
                    servletInputStream);
            byte[] buf = new byte[1024];
            int len = buf.length;
            int offset = 0;
            servletInputStream.mark(buf.length);
            do {
                int inputLen = servletInputStream.read(buf, offset, len
                        - offset);
                if (inputLen <= 0) {
                    break;
                }
                offset += inputLen;
            } while ((len - offset) > 0);
            servletInputStream.reset();

            parameters = new HashMap<String, String>();
            String str = new String(buf, 0, offset,
                    Constants.CHARACTER_ENCODING_UTF8);
            String[] pairs = str.split("&");
            for (int i = 0; i < pairs.length; i++) {
                int idx = pairs[i].indexOf('=');
                if (idx >= 0) {
                    parameters.put(pairs[i].substring(0, idx), URLDecoder
                            .decode(pairs[i].substring(idx + 1),
                                    Constants.CHARACTER_ENCODING_UTF8));
                }
            }
        }
    } catch (IOException e) {
        logger.logError(
                Log4jLogger.SYSTEM_LOG,
                e,
                LogMessageIdentifier.ERROR_ACCESS_INPUT_STREAM_OF_REQUEST_FAILED);
    }
}
 
Example 20
Project: febit   File: MultipartRequestWrapper.java   View Source Code Vote up 4 votes
public void parseRequestStream(String encoding) throws IOException {
    if (parsed == true) {
        throw new IOException("Multi-part request already parsed");
    }
    parsed = true;

    final HttpServletRequest request = this.request;

    //parse queryString
    String queryString = request.getQueryString();
    if (queryString != null && !queryString.isEmpty()) {
        for (String raw : StringUtil.splitc(queryString, '&')) {
            int split = raw.indexOf('=');
            if (split >= 0) {
                putParameter(decodeUrl(raw.substring(0, split)).trim(),
                        decodeUrl(raw.substring(split + 1)).trim());
            } else {
                putParameter(decodeUrl(raw).trim(), "");
            }
        }
    }

    final MultipartRequestInputStream input = new MultipartRequestInputStream(request.getInputStream());
    input.readBoundary();
    while (true) {
        MultipartRequestHeader header = input.readDataHeader(encoding);
        if (header == null) {
            break;
        }

        if (header.isFile == true) {
            String fileName = header.fileName;
            if (fileName.length() > 0) {
                if (header.contentType.indexOf("application/x-macbinary") > 0) {
                    input.skipBytes(128);
                }
            }
            UploadFile newFile = fileUploadFactory.create(input);
            putFile(header.fieldName, newFile);
        } else {
            // no file, therefore it is regular form parameter.
            FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
            input.copyAll(fbos);
            String value = encoding != null ? new String(fbos.toByteArray(), encoding) : new String(fbos.toByteArray());
            putParameter(header.fieldName, value);
        }

        input.skipBytes(1);
        input.mark(1);

        // read byte, but may be end of stream
        int nextByte = input.read();
        if (nextByte == -1 || nextByte == '-') {
            input.reset();
            break;
        }
        input.reset();
    }
}