HttpUrlConnection响应代码始终返回-1

时间:2012-09-26 06:12:31

标签: http httpurlconnection

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

3 个答案:

答案 0 :(得分:0)

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

Android Https Status code -1

希望有所帮助。

答案 1 :(得分:0)

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

Java Http~URLConnection response code -1

答案 2 :(得分:0)

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