java - URLConnection 错误 - java.io.IOException : Server returned HTTP response code: 400 for URL

标签 java url https

我正在尝试从桌面应用程序连接到 URL,并且我收到问题标题中指示的错误,但是当我尝试从 servlet 连接到相同的 URL 时,一切正常。当我从浏览器加载 URL 时,一切正常。我在 servlet 中使用相同的代码。代码在库中,当它不起作用时,我将代码拉到当前项目中的一个类中,但它不起作用。

网址 https://graph.facebook.com/me .

代码片段。

public static String post(String urlSpec, String data) throws Exception {
    URL url = new URL(urlSpec);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(data);
    writer.flush();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    StringBuilder builder = new StringBuilder();
    while((line = reader.readLine()) != null) {
        builder.append(line);
    }
    return builder.toString();
}   

我在这里有点困惑,是否存在不是普通桌面应用程序的 servlet?

谢谢。

完整的堆栈跟踪

Feb 8, 2011 9:54:14 AM com.trinisoftinc.jiraffe.objects.FacebookAlbum create
SEVERE: null
java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.facebook.com/me
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
        at com.jiraffe.helpers.Util.post(Util.java:49)
        at com.trinisoftinc.jiraffe.objects.FacebookAlbum.create(FacebookAlbum.java:211)
        at com.trinisoftinc.jiraffe.objects.FacebookAlbum.main(FacebookAlbum.java:261)

最佳答案

编辑:您需要找到 facebook 在响应中发送的确切错误消息 您可以修改代码以从错误流中获取消息,如下所示:

HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}

看看你是如何传递用户上下文的 以下是一些可以帮助您的信息:

查看400响应码背后的错误信息:

"Facebook Platform""invalid_request""查询当前用户信息必须使用主动访问 token *

您会找到解决方案 here

HTTP/1.1 400 Bad Request
...
WWW-Authenticate: OAuth "Facebook Platform" "invalid_request" "An active access token must be used to query information about the current user."
...

关于java - URLConnection 错误 - java.io.IOException : Server returned HTTP response code: 400 for URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4931164/

相关文章:

java - JPA OneToOne 加入问题

java - 在 Java 中,是否可以从 try catch block 中返回多个值?

java - intellij 中的 URL myweb_war_exploded 出现问题

jsp - 提交 HTML 表单后,servlet 操作出现在 URL 而不是 JSP 文件中

javascript - 如何使用 javascript 命令在 jw player 中获取源 url

node.js - 如何删除 HTTPS npm 模块中的请求 header

ssl - 在 Microsoft IIS 上将 "HTTPS"重定向到 "HTTP"

java - 使用多个参数过滤数据的最有效方法?

java - logback.xml 的 perf4j 设置

security - 从 HTTP 表单提交到 HTTPS 是否安全?