0. 前言
之前写过接口接收json格式的post请求,当时自己测试返回响应时出现过乱码,但因对方处理说是正常显示,就没有深入思考,最近要写一个发送端,在发送和接收返回响应时都出现过乱码,最后算是解决了,目前尝试过的框架为SpringMVC和jfinal,这两种情况我会分别在最后说明。先说客户端的发送与响应。
1. 样例
1.1 jar包准备
本文中用的json与字符串转换类 net.sf.json.JSONObject
其他转换类都可以,只要符合json格式,在传输过程中都是现转换为json格式的字符串,在转换为字符流传输。
要使用此方法转换,必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:
- commons-lang.jar
- commons-beanutils.jar
- commons-collections.jar
- commons-logging.jar
- ezmorph.jar
- json-lib-2.2.2-jdk15.jar
1.2. 样例
此方法是为了方便自己开发,传入和返回皆为JSONObject,其实本质也可以直接传入和返回字符串,看具体需求吧。
/**
* 向指定URL发送post方法的请求,请求内容为json格式的字符串
* @param urlString
* @param jsonObject
* @return JSONObject 直接返回json对象
*/
public static JSONObject postJson(String urlString ,JSONObject jsonObject) {
JSONObject returnJson = null;
try {
// 创建连接
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");//**注意点1**,需要此格式,后边这个字符集可以不设置
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.write(jsonObject.toString().getBytes("UTF-8"));//**注意点2**,需要此格式
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));//**注意点3**,需要此格式
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
sb.append(lines);
}
System.out.println("sb:"+sb);
returnJson = JSONObject.fromObject(sb.toString());
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnJson;
}
2. 分别介绍一下如何用SpringMVC和jfinal接收
2.1. SpringMVC接收
(1)首先开启Spring注解
<mvc:annotation-driven />
(2)其次要添加springMVC需要添加如下配置
只提供Spring4.x的配置,3的配置差不多,自己搜一下吧
配置文件
spring4.x配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<!-- 注意 这是传输json格式,无论是ajax还是外部接口传输-->
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
(3)最后controller中接收
//接收实体中可以用三种方式,本质是Map格式的实体,HttpEntity格式需要getbody()才可以获取json格式的字符串,也可以传实体类,项目因为接收数据复杂,还需保存原始数据,所以没有用实体类。
@RequestMapping(value = "你的地址",method=RequestMethod.POST,consumes="application/json")
@ResponseBody()
public Object dataReceive(@RequestBody JSONObject obj ,ServletRequest request){
return JSONObject;//json对象
}
public Object dataReceive(HttpEntity<JSONObject> obj ,ServletRequest request){
return JSONObject;//json对象
}
public Object dataReceive(Map <String,Object>m ,ServletRequest request){
return JSONObject;//json对象
}
2.2. jfinal接收
主要是跳过拦截时的方法与SpringMVC不一样。
@Clear//跳过验证(例如session)
public void index() {
StringBuilder json = new StringBuilder();
try {
HttpServletRequest request = this.getRequest();
BufferedReader reader = request.getReader();
String line = null;
while ((line = reader.readLine()) != null) {
json.append(line);
}
reader.close();
} catch (Exception e) {
// TODO: handle exception
}
JSONObject json= JSONObject.fromObject(json.toString());
...
...
renderJson(你要返回的json对象);
}
如果有什么错误的地方,请大家指出。