package com.nnk.upstream.controller;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Created with IntelliJ IDEA.
* User: y
* Date: 2016/6/12
* Time: 9:30
* email: xxydliuy@163.com
* To change this template use File | Settings | File Templates.
*/
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] body;
public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = StreamUtils.copyToByteArray(request.getInputStream());
String contentType = request.getContentType();

System.out.println("contentType:" + contentType);
System.out.println("body length:" + body.length);
}

@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}

@Override
public boolean isFinished() {
return false;
}

@Override
public boolean isReady() {
return false;
}

@Override
public void setReadListener(ReadListener readListener) {

}
};

}

@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}

[quote]过滤器配置[/quote]

package com.nnk.upstream.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
* Created with IntelliJ IDEA.
* User: y
* Date: 2016/6/12
* Time: 9:35
* email: xxydliuy@163.com
* To change this template use File | Settings | File Templates.
*/
@WebFilter(filterName = "HttpReplaceFilter",urlPatterns="/*")
public class HttpReplaceFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = null;

if(request instanceof HttpServletRequest) {
if(((HttpServletRequest) request).getMethod().equalsIgnoreCase("post")) {
requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) request);
}
}
if(null == requestWrapper) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
}
}

@Override
public void destroy() {

}
}

[quote]springboot 对过滤器的支持需要使用@ServletComponentScan相关注解[/quote]


@Configuration
@ComponentScan("com.nnk.upstream")
@EnableAutoConfiguration
@ImportResource("classpath:/context/bean.xml")
@ServletComponentScan
public class SampleIntegrationApplication extends SpringBootServletInitializer {
public static final Logger LOGGER = Logger.getLogger(SampleIntegrationApplication.class);
public static String IntanceKey;
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleIntegrationApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleIntegrationApplication.class, args);
}
}

[quote]使用httpClient请求Url会发现无法获取到流数据,如果是contentType:application/x-www-form-urlencoded; charset=UTF-8但是如果是contentType:text/plain; charset=GBK则可以获取流数据。流数据只能被读取一次,而且跟请求类型有关系[/quote]


package com.nnk.redis;

import com.nnk.upstream.core.ConfigContextManager;
import com.nnk.upstream.entity.parterner.CallbackRequest;
import com.nnk.upstream.util.ReflectUtils;
import com.nnk.upstream.util.SignSecurityUtlis;
import com.nnk.upstream.vo.InterfaceConfig;
import com.nnk.utils.http.exception.NetWorkException;
import com.nnk.utils.http.interfaces.HttpData;
import com.nnk.utils.http.utils.HttpClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.nio.charset.Charset;

/**
* Created with IntelliJ IDEA.
* User: y
* Date: 2016/4/25
* Time: 9:49
* email: xxydliuy@163.com
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:context/bean.xml" })
public class CallbackTest {
private Logger logger = Logger.getLogger(CallbackTest.class);
@Autowired
private HttpClientUtils httpClientUtils;
@Autowired
private ConfigContextManager configContextManager;
@Test
public void testCallbackSuccess() throws NetWorkException {

CallbackRequest request = new CallbackRequest();
request.setOrderStatus("SUCCESS");
request.setRespCode("0000");
request.setRealValue("100");
request.setOemorderId("oemH89898709909");
request.setSendorderId("29038297439284320");
request.setMerchantNo("2000000011");
InterfaceConfig config = configContextManager.searchConfigContext("20000009");
request.setRespMsg("成功");
String signStr = ReflectUtils.getkeyValueString(request,"=","&","sign");
String sign = SignSecurityUtlis.sign(signStr,"123456");
request.setSign(sign);
String Resp = httpClientUtils.doPost("http://localhost:8099/Upstream/coustomizeCallback?merid=200000009",request);

}
@Test
public void testCallbackSuccess1() throws NetWorkException {

String Resp = httpClientUtils.doPost("http://localhost:8099/Upstream/coustomizeCallback?merid=200000009",new HttpData() {
@Override
public HttpEntity getPostdata() {
return new StringEntity("a=a&b=b", Charset.defaultCharset());
}

@Override
public String getGetdata() {
return null;
}
});

}
}

[quote]关于SpringMVc获取参数:请参看:http://json20080301.iteye.com/blog/1874074?utm_source=tuicool;
http://hw1287789687.iteye.com/blog/2199295[/quote]

SpringMVC获取HttpClient 请求的数据的更多相关文章

  1. php获取 POST请求的数据

    普通键值对的数据: $_POST[‘username’]; // 获取 username的信息: $_REQUEST; //则会获取 整个请求中的键值对,返回结果为数组: 如果是,流数据,则需要使用: ...

  2. jquery中获取ajax请求返回数据的方法

    function getPageTotalAndDataTotal(page) { //设置一个变量用于接收ajax返回的值 var pageTotal = 0; // 获取页数与数据总数 $.aja ...

  3. httpclient 请求 json 数据

    基于\httpcomponents-client-4.5.5需要引入相关jar包如下: 必须导入commons-logging-1.2.jar,否则会提示 json api接口地址: https:// ...

  4. springMVC中接收请求参数&&数据转发

    ### 1. 接收请求参数 #### 1.1. [不推荐] 通过HttpServletRequest获取请求参数 假设存在: <form action="handle_login.do ...

  5. android 获取http请求json数据

    package com.my.gethttpjsondata; import java.io.BufferedReader;import java.io.ByteArrayOutputStream;i ...

  6. Servlet Struts2 SpringMVC 获取参数与导出数据 方法比较

    servlet中通过request.getParameter()从网页获取参数 通过request session servletContext几个域对象的setAttribute(String ,O ...

  7. 在SpringMVC获取客户端传递的数据的方式

    在处理请求的方法中,加入相对应的形参,保证形参参数名和传递的数据的参数名保持一致,就能够自动赋值 value:当不满足赋值条件时,可以使用value属性,指定映射关系 required:设置形参是否必 ...

  8. HttpClient请求网络数据的Post请求

    new Thread(){            public void run() {                                try { //获得输入框内容          ...

  9. SpringMVC跨重定向请求传递数据

    (1)使用URL模板以路径变量和查询参数的形式传递数据(一些简单的数据) @GetMapping("/home/index") public String index(Model ...

随机推荐

  1. 六十九:flask上下文之线程隔离的g对象的使用

    保存全局对象的g对象g对象是在整个flask应用运行期间都是可以使用的,并且也是和request一样,是线程隔离的,这个对象是专门用来存放开发者自己定义的一些数据,方便在整个flask程序中都可以使用 ...

  2. 如何实现Eclipse默认编码为UTF-8

    1 Window->Preferences->General->Workspace,右边Text file encoding选择Other->UTF-8 2 Window-&g ...

  3. 059. Spiral Matrix II

    题目链接:https://leetcode.com/problems/spiral-matrix-ii/description/ Given a positive integer n, generat ...

  4. mysql 索引失效的几种情况+

  5. 继承以及Super

    一个小小的总结,主要关注以下三个问题:ES5的继承方式,ES5的继承与ES6的继承的区别,ES6的super的几种使用方式以及其中this的指向. From http://supermaryy.com ...

  6. Android开发 发布相关知识

    1 三种BuildSystem简介 注意:ADT不要用了,在2017版本已经没有了.而且这就是一个巨坑,以前打包cocos的时候,学习的时候用这个,ADT是eclipse中的一个集成的东东,已经绝版, ...

  7. CornerNet-Lite算法笔记

    论文名称:CornerNet-Lite: Efficient Keypoint Based Object Detection 论文链接:https://arxiv.org/abs/1904.08900 ...

  8. Leetcode之动态规划(DP)专题-931. 下降路径最小和(Minimum Falling Path Sum)

    Leetcode之动态规划(DP)专题-931. 下降路径最小和(Minimum Falling Path Sum) 给定一个方形整数数组 A,我们想要得到通过 A 的下降路径的最小和. 下降路径可以 ...

  9. 华为HCNA乱学Round 4:RIP

  10. jmeter-ERROR o.a.j.p.j.c.DataSourceElement: JDBC data source already defined for: 报错原因

    转载自:https://www.cnblogs.com/zhangfeivip/p/9450403.html Jmeter 多个threadgroup 中的配置元件会一次性进行初始化   例如3个th ...