|
适合有一定基础的阅读,主要学习HttpClient框架如何使用,简单三层结构,包含POST与GET请求,以及获取Cookies和携带Cookies的Demo。
- package bbs.dao;
- import java.text.MessageFormat;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.cookie.Cookie;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import bbs.domain.User;
- public class UserDao {
-
-
- public UserDao() {
- }
-
-
- /**
- * 登录功能
- * [url=home.php?mod=space&uid=275307]@param[/url] user
- * @return
- */
- public String login(User user){
- String url = "http://bbs.125.la/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1";
- try{
- DefaultHttpClient http = new DefaultHttpClient();
- HttpPost request = new HttpPost(url);
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("username",user.getUsername()));
- params.add(new BasicNameValuePair("password",user.getPassword()));
- request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- HttpResponse response = http.execute(request);
- if(response.getStatusLine().getStatusCode() == 200){
- List<Cookie> cookies = http.getCookieStore().getCookies();
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < cookies.size(); i++) {
- Cookie cookie = cookies.get(i);
- sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
- }
- user.setCookies(sb.toString());
- return EntityUtils.toString(response.getEntity());
- }
- }catch(Exception e){
- throw new RuntimeException(e);
- }
- return null;
- }
-
-
- public String queryProfile(String uid , String cookies){
- String url = "http://bbs.125.la/home.php?mod=space&uid={0}&do=profile";
- try{
- url = MessageFormat.format(url, uid);
- DefaultHttpClient http = new DefaultHttpClient();
- HttpGet request = new HttpGet(url);
- request.setHeader("Cookie", cookies);
- HttpResponse response = http.execute(request);
- if(response.getStatusLine().getStatusCode() == 200){
- return EntityUtils.toString(response.getEntity());
- }
- }catch(Exception e){
- throw new RuntimeException(e);
- }
- return null;
- }
-
- }
复制代码
链接:http://pan.baidu.com/s/1dEAuuYl 密码:qhqq
|
评分
-
查看全部评分
|