我希望问题的标题能够准确描述我遇到的问题,但如果没有......
我正在使用 HttpPost 提交表单来登录网站(我的学校),并正在测试看看如果我在用户名/密码字段中输入虚假信息会发生什么;例如,如果我的用户名输入“Kioop”,密码输入“jukli”,我想读取该 HttpResponse。我查看了源代码,了解当我成功登录和没有成功登录时会发生什么,当我没有成功登录时,它会显示一条小错误消息:“无法登录...”但是,当我尝试使用 InputStream 读取该内容时,我只能获得 URL 的原始源代码。抱歉,如果这是一个糟糕的解释,但这是我正在使用的代码:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("https://web.wm.edu/studenthappenings/preview.php?");
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("user", username));
nvps.add(new BasicNameValuePair("pass", password));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httpost);
InputStream input = response.getEntity().getContent();
// writing response to log
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
in.close();
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
最佳答案
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
响应保存在 HttpResponse
的正文中。您可以使用EntityUtils
从HttpResponse
中的HttpEntity
获取string
正文。
关于java - 使用HttpPost提交表单登录后读取URL的HttpResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24392463/