httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件

来源:互联网 发布:esa white 知乎 编辑:程序博客网 时间:2024/06/01 17:08

原文在此:http://renjie120.iteye.com/blog/1727933

但发现需要Session的登陆后再登陆另一个需要登陆的功能页面出错。

package ryan;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpVersion;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.ResponseHandler;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.conn.ClientConnectionManager;import org.apache.http.conn.scheme.PlainSocketFactory;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.cookie.Cookie;import org.apache.http.impl.client.BasicResponseHandler;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpParams;import org.apache.http.params.HttpProtocolParams;import org.apache.http.protocol.BasicHttpContext;import org.apache.http.protocol.HTTP;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;public class HttpClientTotal{public static void getUrl(String url, String encoding)throws ClientProtocolException, IOException{// 默认的Client类HttpClient client = new DefaultHttpClient();// 设置为get取连接的方式HttpGet get = new HttpGet(url);// 得到返回的ResponseHttpResponse response = client.execute(get);// 得到返回的Client里面的实体对象信息HttpEntity entity = response.getEntity();if (entity != null){System.out.println("内容编码是:" + entity.getContentEncoding());System.out.println("内容类型是: " + entity.getContentType());// 得到返回主体内容InputStream is = entity.getContent();try{BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding));System.out.println(reader.readLine());} catch (Exception e){e.printStackTrace();} finally{if (is != null) is.close();}}// 关闭连接client.getConnectionManager().shutdown();}// 简单使用POSt进行public static void postUrlWithParams(String url,Map<String, String> params, String encoding){DefaultHttpClient client = new DefaultHttpClient();try{HttpPost httpPost = new HttpPost(url);// 添加参数List<NameValuePair> nvps = new ArrayList<NameValuePair>();if (params != null && params.keySet().size() > 0){Iterator iterator = params.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> entry = (Entry) iterator.next();nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));HttpResponse response = client.execute(httpPost);HttpEntity entity = response.getEntity();System.out.println("Login form get: " + response.getStatusLine()+ entity.getContent());dump(entity, encoding);System.out.println("Post logon cookies:");List<Cookie> cookies = client.getCookieStore().getCookies();if (cookies.isEmpty()){System.out.println("None");} else{for (int i = 0; i < cookies.size(); i++){System.out.println("- " + cookies.get(i).toString());}}} catch (UnsupportedEncodingException e){e.printStackTrace();} catch (ClientProtocolException e){e.printStackTrace();} catch (IOException e){e.printStackTrace();} finally{// 关闭请求client.getConnectionManager().shutdown();}}private static void dump(HttpEntity entity, String encoding)throws IOException{BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), encoding));System.out.println(br.readLine());}/** * 4.常见的登录session问题,需求:使用账户,密码登录系统之后,然后再访问页面不出错。 *  * @param url * @param params * @param encoding * @param url2 * @return * @throws Exception */public static String getSessionId(String url, Map params, String encoding,String url2) throws Exception{DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());try{HttpPost httpPost = new HttpPost(url);// 添加参数List<NameValuePair> nvps = new ArrayList<NameValuePair>();if (params != null && params.keySet().size() > 0){Iterator iterator = params.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> entry = (Entry) iterator.next();nvps.add(new BasicNameValuePair((String) entry.getKey(),(String) entry.getValue()));}}// 设置请求的编码格式httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));// 登陆一遍httpClient.execute(httpPost);httpPost = new HttpPost(url2);BasicResponseHandler responseHandler = new BasicResponseHandler();// 再登陆System.out.println(httpClient.execute(httpPost, responseHandler));} finally{// 关闭请求httpClient.getConnectionManager().shutdown();}return "";}// 第一个参数,网络连接;第二个参数,保存到本地文件的地址public static void getFile(String url, String fileName){HttpClient client = new DefaultHttpClient();HttpGet get = new HttpGet(url);try{ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>(){public byte[] handleResponse(HttpResponse response)throws ClientProtocolException, IOException{HttpEntity entity = response.getEntity();if (entity != null){return EntityUtils.toByteArray(entity);} else{return null;}}};byte[] charts = client.execute(get, handler);FileOutputStream out = new FileOutputStream(fileName);out.write(charts);out.close();} catch (Exception e){e.printStackTrace();} finally{client.getConnectionManager().shutdown();}}//创建一个多线程环境下面可用的httpClientprivate static HttpClient createHttpClient(){HttpParams params = new BasicHttpParams();HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);HttpProtocolParams.setUseExpectContinue(params, true);SchemeRegistry schReg = new SchemeRegistry();schReg.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));schReg.register(new Scheme("https",PlainSocketFactory.getSocketFactory(),433));ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);return new DefaultHttpClient(conMgr,params);}}

原创粉丝点击