1. 程式人生 > >java請求第三方介面遇到的跨域問題

java請求第三方介面遇到的跨域問題

自己專案中遇到的請求第三方介面跨域的問題:

首先專案中引入解決跨域的三個公共包;

包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;

}