BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; } } 接下来就是使用HttpClient,代码类似的,我做了相同的实验,结果就直接出来了,HttpClient会自动的管理Session,第二次请求不需要手动去设置Session就可以登录上。复制代码 代码如下: public class NetClient {
private HttpClient client = null;
public NetClient() { client = new DefaultHttpClient(); }
public String request(String url) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(url); HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; }
public String login(String url) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(url);
//设置post参数的方式还真是不人性化啊…… ArrayList NameValuePair pa = new ArrayList NameValuePair pa.add( new BasicNameValuePair( "username", "admin")); pa.add( new BasicNameValuePair( "password", "admin")); post.setEntity( new UrlEncodedFormEntity(pa, "UTF-8")); HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String data = ""; String line = ""; while ((line = br.readLine()) != null) { data = data + line; } return data; } } 最后总结一下,Session验证的方式是在一次会话中,为每一个客户端都生成了一个SESSIONID,如果是成功登陆的,服务器端就会记录好,登陆成功的SESSIONID,如果登陆失败或者新的SESSIONID,都将无法验证登陆,这就是SESSION验证登陆的基本情况。而HttpURLConnection和HttpClient这两个类都可以用来网络请求,但稍有不同,HttpuRLConnection每一次请求都是新的会话,如果需要去验证SESSIONID,就必须手动的去设置Header,HttpClient就能智能的管理Session,不需要手动设置,实际上HttpClint就类似于一个程序中的小浏览器。最大的槽点我觉得就是这两个类设置post参数的方式都很2B一点都不方便……另外HttpClient不能同时发送两次请求,如果一个请求还没有结束或者关闭,又马上开启另一个请求。就会报警告,截个图吧