【问题标题】:Error 302 when communicating java with google-app-engine与 google-app-engine 通信 java 时出现错误 302
【发布时间】:2011-10-26 21:36:48
【问题描述】:

我正在运行用于从 google-app-engine Web 服务 (testeserjaum.appspot.com) 获取信息的 java 代码,但它总是在第一个 System.out.println 和 null 上打印 {null=[HTTP/1.1 302 Found], Date=[Wed, 26 Oct 2011 21:02:46 GMT], Content-Length=[0], Location=[https://testeserjaum.appspot.com/], Content-Type=[text/html], Server=[Google Frontend]}第二个。

有趣的事实是,与其他 google-app-engine Web 服务一起,该代码可以完美运行(我尝试使用 testegelfur.appspot.com 并且它有效)。

代码如下:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLConnectionReader {
    public static void main(String[] args) throws MalformedURLException, IOException{
           URL url = new URL("http://testeserjaum.appspot.com/");
           HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
           System.out.println(urlConnection.getHeaderFields());
           try {
             InputStream in = new BufferedInputStream(urlConnection.getInputStream());
             BufferedReader buff = new BufferedReader(new InputStreamReader(in));
             System.out.println(buff.readLine());
           }finally{
             urlConnection.disconnect();
           }

    }
}

而且,我不知道它是否有帮助,但这是一个实际有效的 python 等价物。我不能使用它,因为我打算在一个android应用程序上使用这个软件,并且我已经完成了大量的软件,所以这必须在java中完成。

import urllib2
import base64

req = urllib2.Request('http://testeserjaum.appspot.com/')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
#base64string = base64.encodestring('%s:%s' %('user', 'pass'))
#print base64string
#req.add_header("Authorization", "Basic %s" %base64string)
lol = urllib2.urlopen(req)
print lol.read()

【问题讨论】:

  • 请在问题中包含您的代码,而不是粘贴箱。 Pastebins 有消失的趋势,它也使问题更难阅读。我已编辑您的问题以添加内联代码。

标签: java android http google-app-engine


【解决方案1】:

HTTP 302 是重定向,而不是错误。这就是为什么它被称为找到

具体来说,它告诉客户端获取https://testeserjaum.appspot.com/ 而不是http://testeserjaum.appspot.com/

如果不想处理重定向,直接访问https://testeserjaum.appspot.com/即可。

【讨论】:

    【解决方案2】:

    这不是错误。这是一个临时重定向,您可以关注它。一些库总是为您遵循重定向;有些人从不这样做。其他人把它留给你。如果库没有,您可以在用户代码中这样做。

    然而,Java 提供了方便的setFollowRedirects 来实现这个目的。

    【讨论】:

    • 我知道,知道为什么会发生这种情况以及如何解决它吗?因为它不会发生在其他 google-app-engine 网络服务上,也不会发生在其他常见网站上(也不会发生在 python 代码上)。
    • 这些服务中的哪一个(testeserjaum、testegelfur 等您有来源)?你知道为什么/如果他们重定向吗?他们可以使用用户代理嗅探来检测 HttpUrlConnection 吗?编辑:似乎其中之一设置为强制使用 HTTPS。它发生在浏览器中,所以我不认为它在嗅探。它可能在 Python 中自动发生,但你没有注意到。
    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 2011-03-23
    • 2021-11-02
    • 2015-09-21
    • 2016-10-28
    • 1970-01-01
    • 2013-10-09
    • 2018-05-27
    相关资源
    最近更新 更多