当前位置: 首页 > news >正文

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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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());
 }
 
}

转载于:https://my.oschina.net/u/1269023/blog/300980

相关文章:

  • SUSE常用命令
  • 开源运维堡垒机(跳板机)系统 Jumpver v0.1.0 架构说明
  • 小米电视屏蔽广告规则
  • 第五章 程序结构
  • VMWare 中安装VMWareTools (Centos系统 和 Windows 系统)
  • bootstarp
  • nginx优化
  • canvas 高仿 Apple Watch 表盘
  • 软件测试(原书第二版)目录
  • 宋江是怎么当上老大的
  • Django之ORM
  • 免费的协作和协同办公软件平台onlyoffice轻松部署
  • 一名游戏开发者的告白
  • docker的Dockerfile指令
  • u3d加载外部视屏
  • 2017年终总结、随想
  • CentOS 7 修改主机名
  • css选择器
  • EventListener原理
  • JavaScript创建对象的四种方式
  • session共享问题解决方案
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • Spring核心 Bean的高级装配
  • SwizzleMethod 黑魔法
  • Work@Alibaba 阿里巴巴的企业应用构建之路
  • 从PHP迁移至Golang - 基础篇
  • 开放才能进步!Angular和Wijmo一起走过的日子
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 一些关于Rust在2019年的思考
  • 移动端唤起键盘时取消position:fixed定位
  • 《码出高效》学习笔记与书中错误记录
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • ​​​​​​​Installing ROS on the Raspberry Pi
  • ​LeetCode解法汇总1276. 不浪费原料的汉堡制作方案
  • # Python csv、xlsx、json、二进制(MP3) 文件读写基本使用
  • (04)odoo视图操作
  • (1)(1.11) SiK Radio v2(一)
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (WSI分类)WSI分类文献小综述 2024
  • (二)springcloud实战之config配置中心
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (附源码)计算机毕业设计ssm基于B_S的汽车售后服务管理系统
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (删)Java线程同步实现一:synchronzied和wait()/notify()
  • (十六)一篇文章学会Java的常用API
  • (原)本想说脏话,奈何已放下
  • (转)C语言家族扩展收藏 (转)C语言家族扩展
  • **PHP分步表单提交思路(分页表单提交)
  • .mysql secret在哪_MySQL如何使用索引
  • .NET Compact Framework 3.5 支持 WCF 的子集
  • .net core IResultFilter 的 OnResultExecuted和OnResultExecuting的区别
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .NetCore Flurl.Http 升级到4.0后 https 无法建立SSL连接
  • .netcore 如何获取系统中所有session_ASP.NET Core如何解决分布式Session一致性问题
  • .NET性能优化(文摘)