//HttpClient httpClient = new DefaultHttpClient();
private void httpGetData() {
new Thread() {
@Override
public void run() {
// 创建一个HttpGet对象
HttpGet httpGet = new HttpGet("http://192.168.1.88:8888/foo/secret.jsp");
try {
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(httpGet);
// handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private void httpPostDate(final String name, final String pass) {
new Thread() {
@Override
public void run() {
try {
HttpPost httPost = new HttpPost("http://192.168.1.88:8888/foo/login.jsp");
// 如果传递参数个数比较多的话可以对传递的参数进行封装
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
// 设置请求参数 // 实现将请求的参数封装到表单中,请求体重
httPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 发送POST请求
HttpResponse response = httpClient.execute(httPost);
// 如果服务器成功地返回响应
if (response.getStatusLine().getStatusCode() == 200) {
String msg = EntityUtils.toString(response.getEntity());
Looper.prepare();
// 提示登录成功
Toast.makeText(HttpClientTest.this, msg, Toast.LENGTH_SHORT).show();
Looper.loop();
// InputStream inputStream = response.getEntity().getContent();
// changeInputStream(inputStream, HTTP.UTF_8);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
// 将一个输入流转换成指定编码的字符串
public static String changeInputStream(InputStream inputStream, String encode) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
如果一开始就使用HttpClient发送get请求,会返回错误,通过HttpClient发送post请求(带有正确的用户名、密码),再次发送get请求即可正常访问被保护的资源,这是因为前面使用了HttpClient登录了系统,而且HttpClient可以维护与服务器之间的Session连接.
// secret.jsp
<%
Object user = session.getAttribute("user");
if(user != null && user.toString().trim().equals("admin"))
{
// 正常页面内容
}
else
{
out.println("您没有被授权访问该页面");
}
%>
// login.jsp
<%
String name = request.getParameter("name");
String pass = request.getParameter("pass");
if (name.equals("admin")&& pass.equals("123"))
{
session.setAttribute("user" , name);
out.println("恭喜您,登录成功!");
}
else
{
out.println("对不起,用户名、密码不符合!");
}
%>
3万+

被折叠的 条评论
为什么被折叠?



