java.io.IOException:服务器返回HTTP响应代码:403为URL https://

时间:2012-09-02 05:08:29

标签: java

我试图通过浏览器访问URL没有问题但是我的程序抛出: java.io.IOException:服务器返回HTTP响应代码:403为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;
    }
}

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

3 个答案:

答案 0 :(得分:1)

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

  

“服务器理解了请求,但拒绝履行请求。授权无效,请求不应重复。”

您需要联系您尝试与之对话的服务器的管理员,以找出为什么禁止请求。可能是他们没有启用https,或者它可能是与使用https无关的问题。

答案 1 :(得分:0)

您无权访问网址/资源。点击http://en.wikipedia.org/wiki/HTTP_403

答案 2 :(得分: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;
    }
}