连接Http Server的代码

连接Http Server的代码很多,最近我看到一份资料中连接HTTP代码不错,
只是对于他使用ByteArrayOutputStream来in.read()没有理解,哪位能够指点?


String url = "http://www.developnet.co.uk/SerializeServlet";
HttpConnection conn = (HttpConnection) Connector.open(url);

conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(
"Content-Type", "application/octet-stream ");
conn.setRequestProperty(
"User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
conn.setRequestProperty(
"Content-Language", "en-US");
conn.setRequestProperty(
"Accept", "application/octet-stream");
conn.setRequestProperty(
"Connection", "close"); // optional


byte[] data =.....;
//发送请求request
conn.setRequestProperty(
"Content-Length", Integer.toString(data.length));
OutputStream os = conn.openOutputStream();
os.write(data);
os.close();

//以下是接受response
int rc = conn.getResponseCode();
if (rc == HttpConnection.HTTP_OK)
{
int len = (int)conn.getLength();
InputStream in = conn.openInputStream();
if (len != -1)
{
int total = 0;
data = new byte[len];
while (total < len)
{
total += in.read(data, total, len - total);
}
}
else
{
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1)
{
tmp.write(ch);
}
data = tmp.toByteArray();
}

//将data处理
.............

}

如果conn.getLength()返回-1,表示这个http response的content-length不确定(即response头里没有提供content-length这一属性或属性值不是valid的),则客户端必须一直接收数据,直到服务器主动关闭socket。这是HTTP协议中的东东。

所以上面的程序中用了一个字节缓冲,并且in.read()到-1值,表示服务端已经关闭连接了。

关键是 tmp.write(ch);
将ch写入数组,ch是读字节的计数,应该是将读的内容写入数组啊

JavaDoc 里有说明
read 和 read(...) 返回的东西是不同的

同意楼上。
最近一直在弄下载的操作,其中关键代码就用了
while ((ch = in.read()) != -1)
将读的内容写到ch里面,如果读到末尾,也就是读的内容为null,就返回-1.

in.read()返回的是int型的字节值,所以它的范围应该在0到255之间,如果返回-1,则表示到了末尾。如果为了清晰可见,可以如此写语句:

int byteValue = 0;

while((byteValue = in.read()) != -1) {
char ch = (char)byteValue;
...
}