【问题标题】:HttpUrlConnection response code always returns -1HttpUrlConnection 响应代码总是返回 -1
【发布时间】:2026-02-12 14:45:01
【问题描述】:

我在亚马逊 ec2 实例中创建了我的服务器。通过我的 android 应用程序,我使用 HttpUrlConnection 连接到服务器。但我得到的响应代码为-1。有没有人有任何想法?这是我的代码。 私有字符串 getHttpResponse(final String 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 

【问题讨论】:

    标签: http httpurlconnection


    【解决方案1】:

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

    Android Https Status code -1

    希望对您有所帮助。

    【讨论】:

    • 感谢您的回复.. 我试过 System.setProperty("http.keepAlive", "false");但遗憾的是它对我不起作用:(..任何其他帮助表示赞赏..
    【解决方案2】:

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

    Java Http~URLConnection response code -1

    【讨论】:

      【解决方案3】:

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

      【讨论】: