java后台调用接口,处理跨域问题

        前言:在做系统的时候,有些时候系统A的js代码需要调用系统B的接口,这就会产生跨域现象,可以通过后台调用处理跨域

问题,这就有点 “代理” 的意思了。

        在这记录一个通用的方法。。。

public String httpPost(String urlStr,Map params){
    URL connect;
    StringBuffer data = new StringBuffer();  
    try {  
        connect = new URL(urlStr);  
        HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
        connection.setRequestMethod("POST");  
        connection.setDoOutput(true); 
        connection.setDoInput(true);
        connection.setUseCaches(false);//post不能使用缓存
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        OutputStreamWriter paramout = new OutputStreamWriter(  connection.getOutputStream(),"UTF-8"); 
        String paramsStr = "";   //拼接Post 请求的参数
        for(String param : params.keySet()){
           paramsStr += "&" + param + "=" + params.get(param);
        }  
        if(!paramsStr.isEmpty()){
            paramsStr = paramsStr.substring(1);
        }
        paramout.write(paramsStr);  
        paramout.flush();  
        BufferedReader reader = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream(), "UTF-8"));  
        String line;              
        while ((line = reader.readLine()) != null) {          
            data.append(line);            
        }   
        paramout.close();  
            reader.close();  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
       return data.toString();
}

 

你可能感兴趣的:(Java)