本文介绍了HttpConnection - javax.microedition,为getLength()方法返回-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用java编写一个非常简单的移动应用程序(J2ME)。我们的想法是通过URL输入访问网站,并将网站内容读入缓冲区。

I am trying to program a very simple Mobile Application (J2ME) in java. The idea is to access a website via URL input and read the contents of the website into a buffer.

这是问题所在。这适用于某些URL,但不适用于其他URL?下面的例子(维基百科)工作正常。但是以http://java.com/en/about/为例,HttpConnection hc为getLenght()返回-1,因此没有内容可以读入缓冲区?

Here's the problem. This works perfectly fine for some URL's but not others? The example below (wikipedia) works fine. But take "http://java.com/en/about/" as an example and the "HttpConnection hc" returns -1 for getLenght() so there is no content to read into the buffer?

这是我的代码:

        String url = "http://en.wikipedia.org/wiki/RSS";

        //Sets up HttpConnection and InputStream using the URL variable
        HttpConnection hc = null;
        InputStream is = null;

        try {
            hc = (HttpConnection) Connector.open(url);
            is = hc.openInputStream();
        } catch (IOException ie) {
            System.out.println(ie.getMessage());
        }

        //Reader object created to read input from InputStream
        Reader rdr = new InputStreamReader(is);

        //Variable "content" will store HTML code
        String content = "";

        //Get the lenght of the data to set the buffer sizes
        int len = (int) hc.getLength();

任何想法?如果我遗漏了任何内容,请告诉我!

Any ideas? let me know if I've missed anything out!

仅供参考我使用的是Netbeans 6.9.1

Just for info I am using Netbeans 6.9.1

HttpConnection的库是javax.microedition.io.HttpConnection; +import javax.microedition.io.Connector;

Library for HttpConnection is "javax.microedition.io.HttpConnection;" + "import javax.microedition.io.Connector;"

推荐答案

来自java.com的HTTP响应是

The HTTP response from java.com is

HTTP/1.1 200 OK
Server: Sun-Java-System-Web-Server/7.0
Date: Wed, 23 Feb 2011 11:07:44 GMT
Content-Type: text/html;charset=UTF-8
Set-Cookie: JSESSIONID=B62F3DFB233BB2806018EC721F6C3FD7; Path=/
Content-Encoding: gzip
Vary: accept-encoding
Transfer-Encoding: chunked

来自维基百科的HTTP响应是

The HTTP response from wikipedia is

HTTP/1.0 200 OK
Date: Wed, 23 Feb 2011 10:18:56 GMT
Server: Apache
Cache-Control: private, s-maxage=0, max-age=0, must-revalidate
Content-Language: en
Vary: Accept-Encoding,Cookie
Last-Modified: Fri, 18 Feb 2011 00:23:59 GMT
Content-Encoding: gzip
Content-Length: 24905
Content-Type: text/html; charset=UTF-8
Age: 2984
X-Cache: HIT from sq61.wikimedia.org, MISS from sq38.wikimedia.org
X-Cache-Lookup: HIT from sq61.wikimedia.org:3128, MISS from sq38.wikimedia.org:80
Connection: keep-alive

如您所见,的HTTP响应不包含Content-Length标头,内容被分块。

As you see, the HTTP response of http://java.com/en/about/ doesn't contain Content-Length header, the content is chunked.

因此,getLength()返回-1。

So, the getLength() return -1.

这篇关于HttpConnection - javax.microedition,为getLength()方法返回-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 00:33