码迷,mamicode.com
首页 > 其他好文 > 详细

《PC端通过http的方式请求并带上cookie》

时间:2014-08-14 11:06:48      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:http   java   os   io   for   ar   cti   amp   

package com.landray.kmss.app.oa.sign.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
public class HttpUtils {
 protected final static String HTTP_CHARSET = "UTF-8";
 
 public static CookieStore doLogin(String urlPath,String loginName, String loginPass) {
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpParams httpParams = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(httpParams, 5000);  
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
  try {
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("j_username", loginName));
    pairs.add(new BasicNameValuePair("j_password", loginPass));
    urlPath += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs,
        HTTP_CHARSET));
    System.out.println(urlPath);
   HttpGet httpGet = new HttpGet(urlPath);
   HttpResponse httpResponse = httpClient.execute(httpGet);
   int statusCode = httpResponse.getStatusLine().getStatusCode();
   if (statusCode != 200) {
    httpGet.abort();
    throw new RuntimeException("HttpClient,error status code :"
      + statusCode);
   }
   return httpClient.getCookieStore();
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   httpClient.getConnectionManager().shutdown();
  }
  return null;
 }
 public static String httpGet(String urlPath, HashMap<String, String> params,
   CookieStore loginCookie) {
  DefaultHttpClient httpClient = new DefaultHttpClient();
  httpClient.setCookieStore(loginCookie);
  HttpParams httpParams = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(httpParams, 5000);  
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
  try {
   if (params != null && !params.isEmpty()) {
    List<NameValuePair> pairs = initUrlParams(params);
    urlPath += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs,
        HTTP_CHARSET));
   }
   HttpGet httpGet = new HttpGet(urlPath);
   HttpResponse httpResponse = httpClient.execute(httpGet);
   int statusCode = httpResponse.getStatusLine().getStatusCode();
   if (statusCode != 200) {
    httpGet.abort();
    throw new RuntimeException("HttpClient,error status code :"
      + statusCode);
   }
   HttpEntity entity = httpResponse.getEntity();
   String result = null;
   if (entity != null) {
    result = EntityUtils.toString(entity, "utf-8");
   }
//   EntityUtils.consume(entity);
   return result;
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   httpClient.getConnectionManager().shutdown();
  }
  return null;
 }
 public static String httpPost(String urlPath, HashMap<String, String> params,
   CookieStore loginCookie) {
  DefaultHttpClient httpClient = new DefaultHttpClient();
  httpClient.setCookieStore(loginCookie);
  HttpParams httpParams = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(httpParams, 5000);  
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
  try {
   if (params != null && !params.isEmpty()) {
    List<NameValuePair> pairs = initUrlParams(params);
    urlPath += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs,
        HTTP_CHARSET));
   }
   HttpGet httpGet = new HttpGet(urlPath);
   HttpResponse httpResponse = httpClient.execute(httpGet);
   int statusCode = httpResponse.getStatusLine().getStatusCode();
   if (statusCode != 200) {
    httpGet.abort();
    throw new RuntimeException("HttpClient,error status code :"
      + statusCode);
   }
   HttpEntity entity = httpResponse.getEntity();
   String result = null;
   if (entity != null) {
    result = EntityUtils.toString(entity, "utf-8");
   }
//   EntityUtils.consume(entity);
   return result;
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   httpClient.getConnectionManager().shutdown();
  }
  return null;
 }
 private static List<NameValuePair> initUrlParams(
   HashMap<String, String> params) {
  List<NameValuePair> pairs = new ArrayList<NameValuePair>(
    params.size());
  for (Map.Entry<String, String> entry : params.entrySet()) {
   String value = entry.getValue();
   if (value != null) {
    pairs.add(new BasicNameValuePair(entry.getKey(), value));
   }
  }
  return pairs;
 }
 
// public static String get(String urlPath,String cookieId) throws IOException{
//  URL url = new URL(urlPath);
//  // 发送http请求
//  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//  // 传入单点登录token
//  conn.setRequestProperty("Cookie", cookieId);
//  conn.connect();
//  InputStream is = conn.getInputStream();
//  BufferedReader reader = new BufferedReader(new InputStreamReader(
//    is, "utf-8"));
//  StringBuffer buf = new StringBuffer();
//  String line = null;
//  while ((line = reader.readLine()) != null) {
//   buf.append(line);
//  }
//  is.close();
//  // 释放连接
//  conn.disconnect();
//  // 得到xml
//  return buf.toString();
// }
 
 public static void main(String[] args) {
  String urlPath = "http://192.168.0.158:8080/ekp/";
  String loginName = "admin";
  String loginPass = "1";
  CookieStore cookie = doLogin(urlPath + "j_acegi_security_check", loginName, loginPass);
  List<Cookie> cookies = cookie.getCookies();
  String cookieId = null;
  for (Cookie c : cookies) {
   System.out.println(c.getName() + " : " + c.getValue());
   cookieId = c.getValue();
  }
  urlPath += "km/review/km_review_index/kmReviewIndex.do?method=list&nodeType=TEMPLATE&q.fdTemplate=147ce24167648cf71c389ff4e7295d0e&orderby=docCreateTime&ordertype=down&__seq=";
  System.out.println(urlPath);
  String httpGet = httpGet(urlPath, null, cookie);
  System.out.println(httpGet.trim());
 }
 
}

《PC端通过http的方式请求并带上cookie》,布布扣,bubuko.com

《PC端通过http的方式请求并带上cookie》

标签:http   java   os   io   for   ar   cti   amp   

原文地址:http://my.oschina.net/u/1269023/blog/300980

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!