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. LoadRunner参数化详解

    LoadRunner参数化详解 距离上次使用loadrunner 已经有一年多的时间了.初做测试时在项目中用过,后面项目中用不到,自己把重点放在了工具之外的东西上,认为性能测试不仅仅是会用工具,最近又 ...

  2. linux 基础 yum 安装

    ls /dev/cdrom mkdir /mnt/cdrom mount -r /dev/cdrom /mnt/cdrom

  3. js 事件驱动机制

    1.浏览器端的事件驱动机制 javascript 在浏览器端运行是单线程的,这是由浏览器决定的,这是为了避免多线程执行不同任务会发生冲突的情况.也就是说我们写的javascript 代码只在一个线程上 ...

  4. centos升级glibc2.23编译安装

    wget http://ftp.gnu.org/gnu/glibc/glibc-2.23.tar.gz tar -zxvf glibc-2.23.tar.gz cd glibc-2.23 mkdir ...

  5. CentOS的SVN服务器搭建与自动部署全过程

    CentOS的SVN服务器搭建与自动部署全过程 http://www.jb51.net/article/106218.htm authz-db = authz 引起的 svn 认证失败 http:// ...

  6. <li>元素的排序

    要点: getElementsByTagName("li")返回的是HTMLCollection对象,这个对象不同于Array对象,不能使用sort()方法进行排序~ 下面方法的要 ...

  7. python中True,False与0,1之间的关系

    demo1 >>> print(True == 1) >>> print(True == 2) >>> print(False == 0) > ...

  8. 旗舰版win7系统中GraphEdit执行Loading a Graph From an External Process失败对策

    操作系统:旗舰版win7 DirectShow SDK: 9.0 IDE环境:VS2008 以下代码参考MSDN: HRESULT AddToRot(IUnknown *pUnkGraph, DWOR ...

  9. 第五次java实验报告

    Java实验报告 班级 计科二班 学号 20188437 姓名 何磊 完成时间2019/10/10 评分等级 实验四 类的继承 实验目的 理解抽象类与接口的使用: 了解包的作用,掌握包的设计方法. 实 ...

  10. 【洛谷P1816】忠诚——ST表做法

    看了两个小时RMQ并位运算,对二进制勉勉强强有了个初步了解,不能说精通(可能今年CSP前都做不到精通),但是记熟板子做做题还是没有问题的 以下是正式题解,相信你看过了题目,我介绍的是ST表的做法(很简 ...