java请求第三方接口遇到的跨域问题

来源:互联网 发布:免费视频编辑软件排行 编辑:程序博客网 时间:2024/05/17 08:09

自己项目中遇到的请求第三方接口跨域的问题:

首先项目中引入解决跨域的三个公共包;

包1:

package com.jeeplus.modules.zzybaseservice;

public class CyzHttpResponse {
    protected String responseText;  
    protected String session;       

    public String getResponseText() {
        return responseText;
    }

    public void setResponseText(String responseText) {
        this.responseText = responseText;
    }

    public String getSession() {
        return session;
    }

    public void setSession(String session) {
        this.session = session;
    }
}

包2:


package com.jeeplus.modules.zzybaseservice;


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;




public class CyzHttpUtils {
    public static final String POST = "POST";
    public static final String GET = "GET";


    public static CyzHttpResponse doHttpPostJson(String strURL, String json, String session) {
        return doHttpPost(strURL, true, json, session);
    }
    public static CyzHttpResponse doHttpGetJson(String strURL, String json, String session) {
        return doHttpGet(strURL, true, json, session);
    }
    public static CyzHttpResponse doHttpPost(String strURL, String param, String session) {
        return doHttpPost(strURL, false, param, session);
    }


    private static CyzHttpResponse doHttpPost(String strURL, boolean jsonParam, String param, String session) {
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(POST); 
            connection.setRequestProperty("Accept", "*/*"); 
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
            if(jsonParam) {
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //JSON锟斤拷式锟斤拷锟斤拷
            }
            else {
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //锟斤拷�?�锟斤拷式锟斤拷锟斤�?
            }
            if(session != null) {
                connection.setRequestProperty("Cookie", session);
            }
            connection.connect();


            if(param != null) {
                out = new DataOutputStream(connection.getOutputStream());
                out.writeBytes(param); 
                out.flush();
                out.close();
            }


            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }


            String sessionText = connection.getHeaderField("Set-Cookie"); 
            connection.disconnect(); 


            CyzHttpResponse httpResponse = new CyzHttpResponse();
            httpResponse.setResponseText(builder.toString());
            httpResponse.setSession(sessionText);
            return httpResponse;
        }
        catch (Exception e) {
            System.out.println("HTTP POST发生异常" + e.getLocalizedMessage());
        }
        finally {
            close(out); 
            close(reader); 
        }


        return null;
    }
    private static CyzHttpResponse doHttpGet(String strURL, boolean jsonParam, String param, String session) {
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(GET); 
            connection.setRequestProperty("Accept", "*/*"); 
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
            if(jsonParam) {
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //JSON锟斤拷式锟斤拷锟斤拷
            }
            else {
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //锟斤拷�?�锟斤拷式锟斤拷锟斤�?
            }
            if(session != null) {
                connection.setRequestProperty("Cookie", session);
            }
            connection.connect();


            if(param != null) {
                out = new DataOutputStream(connection.getOutputStream());
                out.writeBytes(param); 
                out.flush();
                out.close();
            }


            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }


            String sessionText = connection.getHeaderField("Set-Cookie"); 
            connection.disconnect(); 


            CyzHttpResponse httpResponse = new CyzHttpResponse();
            httpResponse.setResponseText(builder.toString());
            httpResponse.setSession(sessionText);
            return httpResponse;
        }
        catch (Exception e) {
            System.out.println("HTTP POST发生异常" + e.getLocalizedMessage());
        }
        finally {
            close(out); 
            close(reader); 
        }


        return null;
    }
    public static void close(Closeable closeable) {
        if (closeable == null) {
            return;
        }


        try {
            closeable.close();
        }
        catch (Exception e) {
            System.out.println("发生异常" + e.getMessage());
            e.printStackTrace();
        }
    }
}


包3:

package com.jeeplus.modules.zzybaseservice;




import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.jeeplus.common.web.BaseController;


@Controller
@RequestMapping(value = "${adminPath}/zzy/zzybase")
public class ZzyBaseMesController extends BaseController {


@RequestMapping(value = "/zzyService")
@ResponseBody
public String zzyService(HttpServletRequest request,HttpServletResponse response) {
String ur=request.getParameter("url");
if (StringUtils.isNotBlank(ur)) {
CyzHttpResponse message = CyzHttpUtils.doHttpGetJson(ur, null, null);
String mes = message.getResponseText();
return renderString(response, mes);
}else{
return renderString(response, "path is error");
}
}
}



前台请求接口拿过来在后台处理跨域:(代码如下)

@RequestMapping(value = "applicationOrderDo")
@ResponseBody
public String applicationOrderDo(HttpServletRequest request,HttpServletResponse response,Page page) {
String url="http://smdt.canquick.com/hold/api/appointment.json";
String office_id=request.getParameter("office_id");
CyzHttpResponse message =CyzHttpUtils.doHttpGetJson(url+"?office_id="+office_id,null,null);//调用解决跨域问题(这里是get请求方式)
String mes = message.getResponseText();
Map map = (Map)JSON.parse(mes); 
String date=((Object)map.get("data")).toString();
List<Map<String,Object>> list=JsonToMap.FromJSONStringToList(date);
/*String total=(String)list.get(0).get("total");
page.setCount(Long.parseLong(total));
System.out.println(page.getCount()+"");
request.setAttribute("", total);*/
//JSONObject mess = JSONObject.parseObject(mes);
String json = JSON.toJSONString(list);
 
 
return json;

}


原创粉丝点击