jsonp跨域问题,SpringMvc跨域远程接口调用

涉及到了ajax跨域问题,以及springmvc 跨域访问远程接口

   @ResponseBody
    @GetMapping("/get_separate_word")
    //required = false 表示接受的值是否是必须的
    public String get_separate_word(@RequestParam(value = "Input",required = false)  String Input)
     throws Exception{
        System.out.println(Input);
        String s1 = null;
        String s2 = null;
        String[] split = Input.split(",");
        //首先判断发送过来的是否为空
        if(split.length==1){
            s1 = Input.replaceAll(",","");
            Gson gson=new Gson();
            Map map=new HashMap();
            //如果为空的话就将返回值返回为空
            map.put("seat","");
            return s1+"("+gson.toJson(map)+")";
       }else{
              s1 = split[0];
              s2 = split[1];
            System.out.println(s1);
            System.out.println(s2);
        }
        DefaultHttpClient hc = new DefaultHttpClient();
        HttpPost post = new 
        HttpPost("http://192.168.50.184:8383/text/segmentation");
        JSONObject obj = new JSONObject();
        //将数据保存到obj中
        obj.put("strings",s2);
        //这个在发送之前要保证格式编码是对的
        StringEntity entity = new StringEntity(obj.toString(),
                ContentType.create("application/json","UTF-8"));
        post.setEntity(entity);
        HttpResponse res = hc.execute(post);
        HttpEntity msg = res.getEntity();
        //msg时得到的后端数据
        String a = EntityUtils.toString(msg, "utf-8");
        //得到的数据是编码的,可以用下面这个,就可以解码
        JsonParser parser = new JsonParser();
        JsonObject jo = parser.parse(a).getAsJsonObject();
        String message = jo.get("result").getAsString();
        System.out.println(message);
        //将收到的数据放到map中,再将map转换成json格式
        Gson gson=new Gson();
        Map map=new HashMap();
        map.put("seat",message);
        System.out.println(s1+"("+gson.toJson(map)+")");
        **//重点!!!!!这个最后的返回格式一定要是callback(json)这样拼接的
        jQuery1111005463873437068156_1544146244509({"seat":"几天 \n"})
         这个形式,前边是验证参数,如果没有这个参数,前端无法识别,就自然不会接受**
        return  s1+"("+gson.toJson(map)+")";
    }```

你可能感兴趣的:(java)