NutzCN Logo
问答 nutz rest 通过 HttpPost无法获取参数
发布于 2256天前 作者 qq_f55c6d47 3368 次浏览 复制 上一个帖子 下一个帖子
标签:

通过http://127.0.0.1:8080/test/test/{ "userName":"Lily", "password":"123456" } 这样后台可以获取NutMap
通过 HttpPost无法获取
后台代码

@At("/jgxx/info")
@Filters({ @By(type = SafeTokenAuthAttribute.class) })
public class test {
	@AdaptBy(type = JsonAdaptor.class)
	@At("/select/?")
	@GET
	@POST
	public String getUser(NutMap jgxx) {
		// TODO 这里是实现代码
		System.out.println("jgxx"+jgxx);
		return "11";
	}
}

httpClient post 参数

/**
	 * 接口调用(post请求) 数据处理
	 *
	 * @param url   请求路径 例如:http://127.0.0.1:8080/test/test
	 * @param param 请求参数 例如:{ "userName":"Lily", "password":"123456" }
	 * @return 响应数据 例如:{ "resultId":"1" "resultMsg":"操作成功" }
	 */
	public static String insureResponsePost(String url, String param) {

		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Accept", "application/json");
			// 设置请求的报文头部的编码
			httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

			// 设置期望服务端返回的编码
			httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
			// httpPost.setHeader("Content-Type", "application/json");
			// String charSet = "UTF-8";
			StringEntity entity = new StringEntity(param, "UTF-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			
			httpPost.setEntity(entity);
			CloseableHttpResponse response = null;
			response = httpClient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity);
				return jsonString;
			} else {
				System.out.println("请求返回:" + state + "(" + url + ")");
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

报错

2018-09-18 15:14:10,842 [WARN][org.nutz.mvc.impl.processor.FailProcessor] - Error@/jgxx/info/select/index :
org.nutz.castor.FailToCastObjectException: Fail to cast from <java.lang.String> to <org.nutz.lang.util.NutMap> for {index.html}
	at org.nutz.castor.Castors.cast(Castors.java:262)
	at org.nutz.castor.Castors.castTo(Castors.java:316)
	at org.nutz.mapl.impl.convert.ObjConvertImpl.convert(ObjConvertImpl.java:69)
	at org.nutz.mapl.Mapl.maplistToObj(Mapl.java:34)
	at org.nutz.mvc.adaptor.injector.JsonInjector.get(JsonInjector.java:34)
	at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:288)
	at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:25)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:58)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:123)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
	at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
	at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
	at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
	at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:218)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.nutz.json.JsonException: !Json syntax error nearby [row:1,col:1 char 'i'], reason: 'Unexpect String = index.html'
	at org.nutz.json.impl.JsonTokenScan.readObject(JsonCompileImplV2.java:304)
	at org.nutz.json.impl.JsonTokenScan.read(JsonCompileImplV2.java:360)
	at org.nutz.json.impl.JsonCompileImplV2.parse(JsonCompileImplV2.java:27)
	at org.nutz.json.Json.fromJson(Json.java:42)
	at org.nutz.json.Json.parse(Json.java:77)
	at org.nutz.json.Json.fromJson(Json.java:58)
	at org.nutz.json.Json.fromJson(Json.java:163)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:14)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:9)
	at org.nutz.castor.Castors.cast(Castors.java:252)
	... 34 more
-----------%7B%22appid%22%3A%22123456%22%2C%22info%22%3A%22%7B%27name%27%2C%27%E6%B5%8B%E8%AF%95%E5%AD%97%E6%AE%B5%27%7D%22%2C%22timestamp%22%3A%221537255361788%22%2C%22sign%22%3A%228fe9500eab998661b484121170f5351d%22%7D
2018-09-18 15:23:03,516 [WARN][org.nutz.mvc.impl.processor.FailProcessor] - Error@/jgxx/info/select/index :
org.nutz.castor.FailToCastObjectException: Fail to cast from <java.lang.String> to <org.nutz.lang.util.NutMap> for {index.html}
	at org.nutz.castor.Castors.cast(Castors.java:262)
	at org.nutz.castor.Castors.castTo(Castors.java:316)
	at org.nutz.mapl.impl.convert.ObjConvertImpl.convert(ObjConvertImpl.java:69)
	at org.nutz.mapl.Mapl.maplistToObj(Mapl.java:34)
	at org.nutz.mvc.adaptor.injector.JsonInjector.get(JsonInjector.java:34)
	at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:288)
	at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:25)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:58)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:123)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
	at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
	at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
	at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
	at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:218)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.nutz.json.JsonException: !Json syntax error nearby [row:1,col:1 char 'i'], reason: 'Unexpect String = index.html'
	at org.nutz.json.impl.JsonTokenScan.readObject(JsonCompileImplV2.java:304)
	at org.nutz.json.impl.JsonTokenScan.read(JsonCompileImplV2.java:360)
	at org.nutz.json.impl.JsonCompileImplV2.parse(JsonCompileImplV2.java:27)
	at org.nutz.json.Json.fromJson(Json.java:42)
	at org.nutz.json.Json.parse(Json.java:77)
	at org.nutz.json.Json.fromJson(Json.java:58)
	at org.nutz.json.Json.fromJson(Json.java:163)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:14)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:9)
	at org.nutz.castor.Castors.cast(Castors.java:252)
	... 34 more
-----------%7B%22appid%22%3A%22123456%22%2C%22info%22%3A%22%7B%27name%27%2C%27%E6%B5%8B%E8%AF%95%E5%AD%97%E6%AE%B5%27%7D%22%2C%22timestamp%22%3A%221537255662434%22%2C%22sign%22%3A%221a92ffdbd5d5d63b448a1053406aae62%22%7D
2018-09-18 15:27:47,133 [WARN][org.nutz.mvc.impl.processor.FailProcessor] - Error@/jgxx/info/select/index :
org.nutz.castor.FailToCastObjectException: Fail to cast from <java.lang.String> to <org.nutz.lang.util.NutMap> for {index.html}
	at org.nutz.castor.Castors.cast(Castors.java:262)
	at org.nutz.castor.Castors.castTo(Castors.java:316)
	at org.nutz.mapl.impl.convert.ObjConvertImpl.convert(ObjConvertImpl.java:69)
	at org.nutz.mapl.Mapl.maplistToObj(Mapl.java:34)
	at org.nutz.mvc.adaptor.injector.JsonInjector.get(JsonInjector.java:34)
	at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:288)
	at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:25)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:58)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:123)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
	at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
	at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
	at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
	at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
	at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
	at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:218)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.nutz.json.JsonException: !Json syntax error nearby [row:1,col:1 char 'i'], reason: 'Unexpect String = index.html'
	at org.nutz.json.impl.JsonTokenScan.readObject(JsonCompileImplV2.java:304)
	at org.nutz.json.impl.JsonTokenScan.read(JsonCompileImplV2.java:360)
	at org.nutz.json.impl.JsonCompileImplV2.parse(JsonCompileImplV2.java:27)
	at org.nutz.json.Json.fromJson(Json.java:42)
	at org.nutz.json.Json.parse(Json.java:77)
	at org.nutz.json.Json.fromJson(Json.java:58)
	at org.nutz.json.Json.fromJson(Json.java:163)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:14)
	at org.nutz.castor.castor.String2Map.cast(String2Map.java:9)
	at org.nutz.castor.Castors.cast(Castors.java:252)
	... 34 more

21 回复

你写的@At,代表第一个参数是路径参数

@At("/select/?")

这样写还是获取不到参数,后台输出null

@At("/jgxx/info")
@Filters({ @By(type = SafeTokenAuthAttribute.class) })
public class test {
	@AdaptBy(type = JsonAdaptor.class)
	@At("/select")
	@GET
	@POST
	public String getUser(String jgxx) {
		// TODO 这里是实现代码
		System.out.println("jgxx"+jgxx);
		return "11";
	}
}
@At("/select")
public String getUser(NutMap re) {
    
}

不行,是不是这样传参不行

StringEntity entity = new StringEntity(param, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);

是不要必须用Header

httpPost.setHeader("apikey", "内容");
httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

这里错了吧

其实用nutz的http库就可以了嘛, 一行写完

Http.post3(....);

改成这样也不行

httpPost.setHeader("Content-type", "application/json; charset=utf-8");

Http.post3(....);没有试,因为该请求是对外的,别人的项目不一定用的是nutz,所有通过HttpPost做的测试。
是不是不支持这种方式请求,只有通过浏览器输入url或ajax请求才能获取参数

肯定支持的, 你先用postman等第三方工具测试好吧

当前是报什么? null吗?

NutMap 参数
System.out.println("jgxx"+jgxx);

public String getUser(NutMap jgxx) {
		// TODO 这里是实现代码
		System.out.println("jgxx"+jgxx);
		return "11";
	}

null 获取不到参数

@At("/jgxx/info")
@Filters({ @By(type = SafeTokenAuthAttribute.class) })
public class test {
	@AdaptBy(type = JsonAdaptor.class)
	@At("/select")
	@GET
	@POST
	public String getUser(@Param("..")NutMap re) {
		System.out.println("re="+re);
		return "11";
	}
}

ContentType一定要设置对

可以了但不是这个问题,因为过滤器ActionContext拿不到post的json参数(经过JsonAdapter解析之后才变成参数)
问题就是下面这段代码

public View match(ActionContext ac) {
		HttpServletRequest request = ac.getRequest();
		JSONObject filterResult = new JSONObject();
		// 将json数据放到String中
		StringBuilder sb = new StringBuilder();
		try {
			InputStreamReader is = null;
			is = new InputStreamReader(request.getInputStream(), request.getCharacterEncoding());
			BufferedReader reader = new BufferedReader(is);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
     return null;
}

在过滤器里通过request.getInputStream()获取参数后,NutMap 就拿不到参数,过滤器@Filters({ @By(type = SafeTokenAuthAttribute.class) })去掉就好了,但是我要获取参数

@At("/jgxx/info")
@Filters({ @By(type = SafeTokenAuthAttribute.class) })
public class test {
	@AdaptBy(type = JsonAdaptor.class)
	@At("/select")
	@GET
	@POST
	public String getUser(@Param("..")NutMap re) {
		System.out.println("re="+re);
		return "11";
	}
}

过滤器通过这种方式获取参数后,所有被过滤的Action 都拿不到参数

InputStreamReader is = null;
			is = new InputStreamReader(request.getInputStream(), request.getCharacterEncoding());
			BufferedReader reader = new BufferedReader(is);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

!!! 那你把filterResult放到req.setAttr吧

@wendal 谢谢!
filterResult放到req.setAttr 还是不行,在看看有没有其他方式吧

放到req之后要从req取呀

但那个逻辑不对的吧,只是读取了数据放到sb变量,然后就没有操作了?好诡异的逻辑

这filter就没写完的吧?纯粹把数据浪费掉了

添加回复
请先登陆
回到顶部