2
我需要在發送POST數據後從URL讀取HTML響應。我已經有了以下兩個功能,但我不知道如何組合它們,以便發送POST數據並獲得響應。通過BlackBerry發送POST數據後獲得HTML響應
該函數獲得一個標準的HTML響應:
public static String getDataFromUrl(String url) throws IOException {
System.out.println("------------FULL URL = " + url + " ------------");
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0;
int ch = 0;
c = (HttpConnection) Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if (len != -1) {
// Read exactly Content-Length bytes
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
// Read until the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
is.close();
c.close();
return b.toString();
}
這個功能發送POST數據到一個URL:
void postViaHttpConnection(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
int rc;
try {
c = (HttpConnection) Connector.open(url);
// Set the request method and headers
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT");
c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-US");
// Getting the output stream may flush the headers
os = c.openOutputStream();
os.write("LIST games\n".getBytes());
os.flush(); // Optional, getResponseCode will flush
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();
// Get the ContentType
String type = c.getType();
processType(type);
// Get the length and process the data
int len = (int) c.getLength();
if (len > 0) {
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ((bytesread != len) && (actual != -1)) {
actual = is.read(data, bytesread, len - bytesread);
bytesread += actual;
}
process(data);
} else {
int ch;
while ((ch = is.read()) != -1) {
process((byte) ch);
}
}
} catch (ClassCastException e) {
throw new IllegalArgumentException("Not an HTTP URL");
} finally {
if (is != null)
is.close();
if (os != null)
os.close();
if (c != null)
c.close();
}
}
所以,我需要知道如何把它們結合在一起,這樣我可以得到響應後發送POST數據。
是(緊急!)我不知道的一些新技術?老實說,描述中的這些東西根本不會幫你。如果你想要緊急的幫助有一個專業的,你付出,站在旁邊。 – rwilliams 2012-03-07 04:27:59
對不起,我很傻。這只是我忽略了我的程序中的這個問題,我需要找到一種方法來儘快解決它。 – Chro 2012-03-07 04:37:08