getAnonymousResolver:配置不允许匿名访问 - 请求凭据

getAnonymousResolver: Anonymous access not allowed by configuration - requesting credentials

我正在使用 CQ5.6 并从服务进行 servlet 调用。在我的错误日志中,我从日志语句中得到 "java.io.IOException: Server returned HTTP response code: 401 for URL: http://localhost:4502/content/sports/jcr:content/parSports/sportsscores.scores"。

如何解决这个问题? (我没有使用凭据做任何事情)

这是我的服务:

mport org.apache.felix.scr.annotations.Activate
import org.apache.felix.scr.annotations.Component
import org.apache.felix.scr.annotations.Properties
import org.apache.felix.scr.annotations.Property
import org.apache.felix.scr.annotations.Service
import org.osgi.service.component.ComponentContext
import org.apache.sling.commons.osgi.PropertiesUtil

@groovy.util.logging.Slf4j
@Component(label = "SportsScoresInit Service", description =
        "Call the servlet that gets the sports scores", immediate = true, metatype =
        true)
@Service(ScoresInterface.class)
@Properties([
        @Property(label = "Dummy", name = "dummy", value = "Default dummy")
])

public class SportsScoresInitial implements ScoresInterface {
    public String scoresFromServlet = "Default"

    public String getScoresFromServlet() {
        setScoresFromServlet()
        return scoresFromServlet
    }
    public void setScoresFromServlet() {
        //date = request.getParameter("date")
        //log.debug("date: {}",date)
        log.debug("In service to call servlet")
        String urlString = "http://localhost:4502/content/sports/jcr:content/parSports/sportsscores.scores"

        log.debug("urlString: " + urlString)
        URL url = null
        HttpURLConnection connection = null
        int responseCode = -9
        String result = ""
        log.debug("Before call to Sports Scores servlet")
        long startTime = System.currentTimeMillis()
        try {
            url = new URL(urlString)
            log.debug("url: " + url)
            connection = (HttpURLConnection) url.openConnection()
            log.debug("Connection: " + connection)
            connection.setRequestMethod("GET")
            responseCode = connection.getResponseCode()
            log.debug("After calling Sports Scores servlet")
            BufferedReader reader
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
            log.debug("reader: " + reader)
            result = reader.readLine()
            long stopTime = System.currentTimeMillis()
            long elapsedTime = stopTime - startTime
            log.debug("Elapsed Time is... " + elapsedTime)
            log.debug("result: " + result)
            PrintWriter writer = response.getWriter()
            response.setContentType("application/json")
            response.setCharacterEncoding("UTF-8")
            //writer.write(result)
        } catch (MalformedURLException e) {
            log.error("MalformedURL")
            e.printStackTrace()
            log.debug("Cause: " + e.getCause())
        } catch (IOException e) {
            log.error("IOException")
            e.printStackTrace()
            log.debug("Cause: " + e.getCause())
        }
        scoresFromServlet = result
    }

}

// Pulls data from OSGi
@Activate
protected void activate(ComponentContext ctx) {
    // Grab property values and store to class variables
    //message = PropertiesUtil.toString(ctx.getProperties().get("message"), "Welcome to this service too")
}

这是我的 servlet:

import org.apache.sling.commons.osgi.PropertiesUtil

import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

import org.apache.sling.api.servlets.SlingSafeMethodsServlet
import org.apache.sling.api.SlingHttpServletRequest
import org.apache.sling.api.SlingHttpServletResponse

import javax.servlet.ServletException




import org.apache.felix.scr.annotations.Activate
import org.apache.felix.scr.annotations.Properties
import org.apache.felix.scr.annotations.Property
import org.apache.felix.scr.annotations.sling.SlingServlet
import org.osgi.service.component.ComponentContext

import groovy.transform.CompileStatic;


@CompileStatic
@groovy.util.logging.Slf4j
@SlingServlet(
        name="sportsScoresServlet",
        resourceTypes="icidigital/components/content/sportsScores",  
        extensions="scores", // put this in the ajax call in the javascript
        methods="GET",
        metatype=true)
@Properties([
        @Property(name="SportsScoresServlet", description="Get JSON String sports scores", value="sports scores")
])

/**
 * Handles requests for getting weather information from OpenWeatherMap.org.  returns the information as a JSon string.
 */
public class SportsScores extends SlingSafeMethodsServlet {


    @Property(label = "The api key", value = 'b0fc12635bbf445aa1a9013c5766fdbf', description = "This is the API Key used to access the Sports Scores API") // register the api key in the OSGi console
    private static final String SPORTS_SCORES_API_KEY = "apikey"


    private String apikey = ""
    private String apikeyTest = ""
    private String date = ""

    @Override
    public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        //System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, 'TRACE');
        //Properties p = new Properties(System.getProperties());
        //System.setProperty(Dorg.slf4j.simpleLogger.defaultLogLevel, 'TRACE');

        log.debug('doGet in SportsScores')
        writeScores(request, response)

    }

    /**
     * Gets current weather information from OpenWeatherMap.org API
     * @param request
     * @param response
     * @throws IOException
     */
    public void writeScores(SlingHttpServletRequest request, SlingHttpServletResponse response)   {
        date = request.getParameter("date")
        log.debug("date: {}",date)
        log.debug("scores api key: {}", apikey)
        String urlString = "http://api.nfldata.apiphany.com/mlb/v2/JSON/BoxScores/${date}?subscription-key=${apikey}"

        log.debug("urlString: " + urlString)
        URL url = null
        HttpURLConnection connection = null
        int responseCode = -9
        String result = ""
        log.debug("Before call to FantasyData")
        long startTime = System.currentTimeMillis()
        try {
            url = new URL(urlString)
            log.debug("url: " + url)
            connection = (HttpURLConnection) url.openConnection()
            log.debug("Connection: " + connection)
            connection.setRequestMethod("GET")
            responseCode = connection.getResponseCode()
            log.debug("After calling FantasyData")
            BufferedReader reader
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
            log.debug("reader: " + reader)
            result = reader.readLine()
            //jsonSlurp(result)
            long stopTime = System.currentTimeMillis()
            long elapsedTime = stopTime - startTime
            log.debug("Elapsed Time is... " + elapsedTime)
            log.debug("result: " + result)
            PrintWriter writer = response.getWriter()
            response.setContentType("application/json")
            response.setCharacterEncoding("UTF-8")
            writer.write(result)
        } catch (MalformedURLException e) {
            log.error("MalformedURL")
            e.printStackTrace()
        } catch (IOException e) {
            log.error("IOException")
            e.printStackTrace()
            log.debug("Cause: " + e.getCause())
        }
    }

    @Activate
    protected void activate(ComponentContext ctx)
    {
        Dictionary dict = ctx.getProperties()
        apikey = PropertiesUtil.toString(dict.get(SPORTS_SCORES_API_KEY),'');

        //apikey = PropertiesUtil.toString(context.getProperties().get("apikey"), "b0fc12635bbf445aa1a9013c5766fdbf") // Get the api key from the OSGi console
        log.debug("sports scores servlet activated")
    }

}

我认为您尝试做的事情没有多大意义。你为什么要对实例本身进行 Http 连接?您正在尝试访问创作实例,这需要访问权限。

看来你是在倒退。您应该有一个服务,您可以在其中访问该第三方服务,然后在您的 servlet 中使用它。这样您就不需要对同一实例使用 http 连接。

话虽如此,如果您仍想通过 CQ5 本身处理请求,则可以使用 SlingRequestProcessor 在内部处理请求,而无需打开实际连接