java实现HTTP的post请求 json格式中文乱码问题

来源:互联网 发布:歌曲剪切合并软件 编辑:程序博客网 时间:2024/06/05 17:53

框架为SpringMVC和jfinal,这两种情况。先说客户端的发送与响应。

  1. 本文中用的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

  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;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

3.分别介绍一下如何用SpringMVC和jfinal接收 
(1)SpringMVC接收 
首先开启Spring注解 

其次要添加springMVC需要添加如下配置 
只提供4的配置,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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

最后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对象    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

(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对象);    }本文转自:http://blog.csdn.net/do_finsh/article/details/70237544?locationNum=13&fps=1
原创粉丝点击