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. spring_quartz的实现

    一.在spring配置文件中引用对应的定时任务配置文件 二.定义定时任务的业务代码 三.配置定时任务配置文件spring-quartz.xml <?xml version="1.0&q ...

  2. 无缝滚动的float属性

    The float CSS property specifies that (1) an element should be taken from the normal flow and (2) pl ...

  3. Window Position

    IE, Safari, Opera, and Chrome all provide screenLeft and screenTop properties that indicate the wind ...

  4. PJzhang:微软出口管制条例

    猫宁!!! 翻译:PJzhang 微软公司的技术,产品和服务受美国出口管理法规(EAR)的约束,由美国商务部工业与安全局(BIS)监督执行. 此外,财政部,国务院对其他与出口相关的技术和产品转让,交易 ...

  5. 闲记Windows 取证艺术

         是不是很好奇,别人能够在你电脑上查看你运行程序历史,文档使用痕迹,浏览器浏览历史种种历史痕迹,没错,通过简单的系统了解以及配合相对应的工具,这一切就是这么的简单,看起来很高大上的操作,其实是 ...

  6. comodo firewall 科莫多离线安装

    comodo firewall是什么?他配有HIPS,配置好规则就可以比杀软强不是一个两个档次,但是新手不建议使用. 注意:不用使用疯狂模式后锁屏,不然系统都打不开. 下载地址: https://do ...

  7. C++多线程基础学习笔记(七)

    一.std::async和std::future的用法 std::async是一个函数模板,std::future是一个类模板 #include <iostream> #include & ...

  8. 与高精死杠的几天——记两道简单的高精dp

    (同样也是noip往年的题 1​.矩阵取数游戏 题目链接[Luogu P1005 矩阵取数游戏] \(\mathcal{SOLUTION}:\) 通过对题目条件的分析,我们可以发现,每一行取数对答案的 ...

  9. 面试40-一个数组,有2个数字出现奇数次,其余都是偶数次,求这两个数字O(n) O(1)

    #include<iostream> using namespace std; // 题目:数组中只有不多于两个数字出现次数是奇数次,其他都是偶数次,求出出现奇数次的数字(不含0的数组) ...

  10. Eratosthenes筛法

    复杂度为nlogn. 算法思想为:枚举1~sqrt(n),然后把每一个数的倍数都都打上不是素数的标记. 还要特别注意0,1不是素数,打标记枚举到i*k<=n. 代码如下 #include< ...