1

我在亚马逊 ec2 实例中创建了我的服务器。通过我的 android 应用程序,我使用 HttpUrlConnection 连接到服务器。但我得到的响应代码为-1。有没有人有任何想法?这是我的代码。私有字符串 getHttpResponse(最终字符串 srcUrl){

    HttpURLConnection urlConnection = null;
    FileOutputStream fos = null;
    try {
        URL url = new URL(srcUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Content-Type", "application/json");
        mETag = readETagFromPrefForCategory();

        urlConnection.setRequestProperty("If-None-Match", mETag);

        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("xyz", "abc".toCharArray());
            }
        });

        urlConnection.connect();

        mETag =  urlConnection.getHeaderField("ETag");

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            Log.v("http","not modifed");
            return readLocalJson();
        }

        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.w(TAG, "Bad response [" + urlConnection.getResponseCode() + "] from (" + srcUrl + ")");
            return null;
        }}//end of try block 
4

3 回答 3

0

这篇文章中的答案似乎为一些人解决了这个问题:

Android Https状态码-1

希望有帮助。

于 2012-09-26T06:37:56.573 回答
0

为什么要在 GET 请求上设置“Content-Type”?

于 2015-02-08T13:46:34.610 回答
0

问题可能是您的标头 HTTP 版本格式不正确。检查这个 SO 链接,我已经回答了一个对我有用的类似问题。

Java Http~URLConnection 响应码 -1

于 2015-02-08T12:09:29.840 回答