• ajax跨域请求


    1、httpclient代理处理跨域请求。

    1.1、请求服务器的xml

    (1)服务器端

    CloseableHttpClient httpClient = HttpClients.createDefault();
    		HttpGet httpGet = new HttpGet("http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=xml&version=1.1&q="+request.getParameter("q"));
    		try {
    			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
    			HttpEntity entity = httpResponse.getEntity();
    			if(entity !=null){
    				String tmp = EntityUtils.toString(entity);
    				httpResponse.close();
    				response.setContentType("text/xml;charset=utf-8");
    				PrintWriter out = response.getWriter();
    				out.print(tmp);
    				out.flush();
    				out.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println(e.getMessage());
    		}finally{
    		}
    

     (2)客户端

    $.ajax({
    					type:"get",
    					url:"/Ajax/fanyi.do",
    					data:"q=good",
    					success:function(xml){
    						var data = "";
    						data += $(xml).find("query").text();
    						data += $(xml).find("translation").text();
    						data += $(xml).find("basic").text();
    						$("#status").text(data);
    					}
    				});
    

    1.2 请求服务器的json格式

    (1)服务器端

    CloseableHttpClient httpClient = HttpClients.createDefault();
    		HttpGet httpGet = new HttpGet("http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=json&version=1.1&q="+request.getParameter("q"));
    		try {
    			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
    			HttpEntity entity = httpResponse.getEntity();
    			if(entity !=null){
    				String tmp = EntityUtils.toString(entity);
    				httpResponse.close();
    				response.setContentType("application/json;charset=utf-8");
    				PrintWriter out = response.getWriter();
    				out.print(tmp);
    				out.flush();
    				out.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println(e.getMessage());
    		}finally{
    		}
    

    (2)客户端

    $.ajax({
    					type:"get",
    					url:"/Ajax/fanyi.do",
    					data:"q=good",
    					success:function(data){
    						$("#status").text(data.translation);
    					}
    				});
    

      

  • 相关阅读:
    bbs树形打印(一)
    ORM
    kafka的分区
    Content-type"是"application/json的作用
    idea增强for循环
    rabbitmq的发布订阅
    搭建mqtt服务器apollo
    kafka生产者集群和分区,消费者轮询接收
    http实时推送技术
    Kafka:Configured broker.id 2 doesn't match stored broker.id 0 in meta.properties.
  • 原文地址:https://www.cnblogs.com/hpustudent/p/4099269.html
Copyright © 2020-2023  润新知