連線Http Server的程式碼

banq發表於2003-01-15
連線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處理
.............

}

相關文章