0

网址:http://monSite/GET.asp

我们必须在获得结果之前进行身份验证。

我想使用相同的 HTTP 客户端发送登录名和密码HttpConn.setRequestMethod (HttpConnection.POST) 并检索 XML 文件。HttpConn.setRequestMethod (HttpConnection.GET)

conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);

postData.append("userName",_username);
postData.append("passWord", _password);


conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");

conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");


// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());

byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();

os.write(postBytes);

os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
        "Profile/MIDP-1.0 Confirguration/CLDC-1.0");

if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;

InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");

while ((len = isr.read(buffer, 0, size)) > 0)
{
    buff.append(buffer, 0, len);
    total += len;
}



result = buff.toString();
} else {
    result = "Error in connection" + conn.getResponseCode();
}


} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    try {
        if (in != null) {
            in.close();
        }
        conn.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

HttpConnection.POST 工作得很好但 GET 否(登录失败:身份验证参数未保存)

4

1 回答 1

0

在 HttpConnection.GET 请求中,您需要在 url 中附加属性,例如:

String url="http://www.xyz?userName="+_username+"&password="+_password+"";

然后获取 InputStream

以下链接可能对您有帮助

http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075

于 2011-07-12T13:42:35.453 回答