-1

我试图通过浏览器访问 URL 没有问题,但是我的程序抛出: java.io.IOException: Server returned HTTP response code: 403 for URL:

这里的 URL 只是我的Sharepoint Online服务器上列表项的附件文件路径。我正在尝试获取该文件的内容。它从浏览器中打开,但从代码中抛出异常。

代码:

private String getAttachmentContent(String attachmentURL) throws IBSharePointException 
{
    InputStream is = null;

    try 
    {
        String fileName=attachmentURL.substring(attachmentURL.lastIndexOf("/")+1);
        String urlPath=attachmentURL.substring(0, attachmentURL.lastIndexOf("/")+1);
        fileName=URLEncoder.encode(fileName, "UTF-8");

        if(fileName.contains("+"))
            fileName=fileName.replace("+", "%20");          
        URL u=new URL(urlPath+fileName);    

        // Following Line Throws Exception : java.io.IOException: Server returned HTTP response code: 403 for URL:
        is = u.openStream();

        ByteArrayOutputStream bais = new ByteArrayOutputStream();
        byte[] byteChunk = new byte[4096];    
        int n;    
        while ( (n = is.read(byteChunk)) > 0 ) 
            { 
                bais.write(byteChunk, 0, n);                    
            }
    }catch(Exception e)
    {
        throw e;
    }
}

我已经完成了代码中的所有设置,甚至尝试了与该主题相关的所有可能解决方案,但仍然无法正常工作。

4

3 回答 3

1

403 Forbidden 响应具有以下记录的含义:

“服务器理解请求,但拒绝执行。授权无济于事,请求不应重复。”

您将需要联系您尝试交谈的服务器的管理员,以了解该请求被禁止的原因。可能是他们没有启用 https,也可能是与使用 https 完全无关的问题。

于 2012-09-02T05:48:47.333 回答
0

您无权访问 URL/资源。在这里查看http://en.wikipedia.org/wiki/HTTP_403

于 2012-09-02T05:33:29.763 回答
0

最后我们找到了解决方案,以下是解决问题。

代码:

private String getAttachmentContent(String attachmentURL) throws IBSharePointException {
    InputStream inputStream = null;
    URLConnection urlConnection = null;
    URL url = null;
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    byte[] byteChunk = new byte[4096];
    int noOfBytes = 0;
    try {

        String fileName = attachmentURL.substring(attachmentURL.lastIndexOf("/") + 1);
        String urlPath = attachmentURL.substring(0, attachmentURL.lastIndexOf("/") + 1);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        //This line is to fix bug # 966837
        if (fileName.contains("+"))
            fileName = fileName.replace("+", "%20");

        url = new URL(urlPath + fileName);
        urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", _Constants.DEFAULT_USER_AGENT_WINDOWS);
        // We need to set cookies as below.
        urlConnection.addRequestProperty("Cookie", _mSharePointSession.cookieNedToken);

        urlConnection.connect();

        inputStream = urlConnection.getInputStream();

        while ((noOfBytes = inputStream.read(byteChunk)) > 0) {
            byteOutputStream.write(byteChunk, 0, noOfBytes);
        }

        return new BASE64Encoder().encode(byteOutputStream.toByteArray());

    } catch (Exception e) {
        throw e;
    }
}
于 2012-09-06T10:47:03.600 回答