• HTTP连接如何保持登录状态?OkHttp或者HttpClient


    上节我们讲过HTTP客户端,基于它们的优劣势,一般使用OkHttp或者HttpClient。所以这节我们主要针对这两个HTTP客户端实现登录一直保持功能。

    OkHttp

    设置cookie请求消息头的方式还可以实现身份认证功能。

     1 // 创建HTTP客户端
     2 OkHttpClient client = new OkHttpClient.Builder()
     3         .cookieJar(new CookieJar() {
     4             // 使用ConcurrentMap存储cookie信息,因为数据在内存中,所以只在程序运行阶段有效,程序结束后即清空
     5             private ConcurrentMap<String, List<Cookie>> storage = new ConcurrentHashMap<>();
     6 
     7             @Override
     8             public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
     9                 String host = url.host();
    10                 if (cookies != null && !cookies.isEmpty()) {
    11                     storage.put(host, cookies);
    12                 }
    13             }
    14 
    15             @Override
    16             public List<Cookie> loadForRequest(HttpUrl url) {
    17                 String host = url.host();
    18                 List<Cookie> list = storage.get(host);
    19                 return list == null ? new ArrayList<>() : list;
    20             }
    21         })
    22         .build();
    23 
    24 final String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
    25 
    26 // 模拟表单登录
    27 Request request = new Request.Builder()
    28         .url("https://www.oschina.net/action/user/hash_login?from=")
    29         .post(new FormBody.Builder()
    30                 .add("email", "修改为你自己的帐号")
    31                 .add("pwd", "修改为你自己的密码,使用SHA-1加密")
    32                 .add("verifyCode", "")
    33                 .add("save_login", "1")
    34                 .build())
    35         .addHeader("User-Agent", userAgent)
    36         .build();
    37 
    38 // 执行模拟登录请求
    39 Response response = client.newCall(request).execute();
    40 
    41 // response status
    42 if (!response.isSuccessful()) {
    43     log.info("code = {}, message = {}", response.code(), response.message());
    44     return;
    45 } else {
    46     log.info("登录成功 !");
    47 }
    48 
    49 
    50 // 请求包含用户状态信息的网页,观察能否正确请求并取得状态信息
    51 request = new Request.Builder()
    52         .url("https://www.oschina.net/")
    53         .addHeader("User-Agent", userAgent)
    54         .get()
    55         .build();
    56 
    57 // 执行GET请求,并在异步回调中处理请求
    58 response = client.newCall(request).execute();
    59 
    60 // 打印登录用户名,验证是否获取到了用户的登录信息(状态信息)
    61 if (response.isSuccessful()) {
    62     String content = response.body().string();
    63 
    64     Matcher matcher = Pattern.compile("<span class="name">(.*)</span>,您好&nbsp;").matcher(content);
    65     if (matcher.find()) {
    66         log.info("登录用户:{}", matcher.group(1));
    67     } else {
    68         log.info("用户未登录");
    69     }
    70 
    71 }

    HttpClient

     1 import org.apache.http.NameValuePair;
     2 import org.apache.http.client.entity.UrlEncodedFormEntity;
     3 import org.apache.http.client.methods.CloseableHttpResponse;
     4 import org.apache.http.client.methods.HttpGet;
     5 import org.apache.http.client.methods.HttpPost;
     6 import org.apache.http.impl.client.CloseableHttpClient;
     7 import org.apache.http.impl.client.HttpClients;
     8 import org.apache.http.message.BasicNameValuePair;
     9  
    10 import java.io.BufferedReader;
    11 import java.io.IOException;
    12 import java.io.InputStream;
    13 import java.io.InputStreamReader;
    14 import java.util.ArrayList;
    15 import java.util.List;
    16  
    17 public class Test  {
    18  
    19     public static void main(String[] args) throws IOException {
    20         InputStreamReader inputStreamReader = null;
    21         BufferedReader reader = null;
    22         String line = null;
    23         //两个页面参数
    24         //据我观察这个url不变
    25         String backUrl = "http%3A%2F%2Fredmine.tvbanywhere.net%2Fredmine%2F";
    26         String authenticityToken = null;
    27  
    28         //创建httpclient对象
    29         CloseableHttpClient httpClient = HttpClients.createDefault();
    30  
    31         //get请求访问这个url是页面
    32         //获取auth_token
    33         HttpGet getParam = new HttpGet("http://redmine.tvbanywhere.net/redmine/login");
    34         CloseableHttpResponse response1 = httpClient.execute(getParam);
    35         InputStream inputStream1 = response1.getEntity().getContent();
    36         inputStreamReader = new InputStreamReader(inputStream1);
    37         reader = new BufferedReader(inputStreamReader);
    38         while ((line = reader.readLine())!= null){
    39             if (line.contains("name="authenticity_token"")){
    40                 System.out.println(line);
    41                 String sub1 = line.substring(line.indexOf("value="") + 7);
    42                 authenticityToken = sub1.substring(0, sub1.indexOf("""));
    43             }
    44         }
    45         reader.close();
    46         inputStreamReader.close();
    47         inputStream1.close();
    48         //post 请求是登录操作
    49         HttpPost dologin = new HttpPost("http://redmine.tvbanywhere.net/redmine/login");
    50         List<NameValuePair> list = new ArrayList<NameValuePair>();
    51         list.add(new BasicNameValuePair("authenticity_token",authenticityToken));
    52         list.add(new BasicNameValuePair("back_url",backUrl));
    53         list.add(new BasicNameValuePair("username","zhongxiaojian@sunniwell.net"));
    54         list.add(new BasicNameValuePair("password","zhongxiaojian@sunniwell.net"));
    55         UrlEncodedFormEntity urlEncodedFormEntity = null;
    56         urlEncodedFormEntity = new UrlEncodedFormEntity(list);
    57         dologin.setEntity(urlEncodedFormEntity);
    58         CloseableHttpResponse response2 = httpClient.execute(dologin);
    59  
    60         HttpGet get1 = new HttpGet("http://redmine.tvbanywhere.net/redmine/search?issues=1&q=howard.tang@tvb.com.hk");
    61         CloseableHttpResponse response3 = httpClient.execute(get1);
    62         System.err.println("get" + get1.getURI());
    63         InputStream inputStream3 = response3.getEntity().getContent();
    64         inputStreamReader = new InputStreamReader(inputStream3);
    65         reader = new BufferedReader(inputStreamReader);
    66         while ((line = reader.readLine()) != null){
    67             System.out.println(line);
    68         }
    69     }
    70 }
  • 相关阅读:
    【arm】using as: GNU assember学习笔记
    【linux】gcc编译选项:-fomit-frame-pointer,-fno-tree-vectorize,-fno-strict-aliasing以及ARM相关选项
    【arm】armv8中通用寄存器的饱和指令实现(对标arm32:ssat,usat,qadd,qsub)
    【shell】常用的几种shell解释器:sh,bash,zsh,ash,csh
    【linux/Tools】Performance Profile Tools——perf and gprof
    【android】如何查看Android设备的CPU架构信息
    【arm】big-LITTLE architecture and How to check core, frequency, features of CPU and memory infos
    【python】创建excel文档.csv
    【mpeg4】MPEG-4 B帧帧间预测模式
    【linux】关于find命令查找的排序规则探索以及排序方法
  • 原文地址:https://www.cnblogs.com/ivy-xu/p/12873549.html
Copyright © 2020-2023  润新知