HttpClient4.5 SSO登录

1.最好先用Jmeter抓取http请求,测试一下,看看哪个请求需要跟随重定向

2.代码如下

  1 public class SSORequest {
  2 
  3  
  4 
  5  public void ssoRequest() {
  6 
  7   StringBuffer ssoCookies = new StringBuffer();
  8 
  9  
 10 
 11   // 1.请求登录接口,从cookie获取soo_auth,放到下一个cookie ;无须重定向(POST默认不允许重定向)
 12 
 13   CloseableHttpClient loginHttpClient = HttpClients.createDefault();
 14 
 15   HttpPost loginPost = new HttpPost("loginUrl");
 16 
 17  
 18 
 19   List formParams = new ArrayList();
 20 
 21   formParams.add(new BasicNameValuePair("returnUrl", "hreturnUrl"));//
 22 
 23   formParams.add(new BasicNameValuePair("username", "userName"));
 24 
 25   formParams.add(new BasicNameValuePair("password", "password"));
 26 
 27  
 28 
 29   try {
 30 
 31    loginPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
 32 
 33    CloseableHttpResponse loginResponse = loginHttpClient.execute(loginPost);
 34 
 35    System.out.println(loginResponse.getStatusLine().getStatusCode());
 36 
 37  
 38 
 39    Header[] t = loginResponse.getAllHeaders();
 40 
 41    for (int i = 0; i < t.length; i++) {
 42 
 43     if ("Set-Cookie".equals(t[i].getName())) {
 44 
 45      ssoCookies.append(t[i].getValue().substring(0, t[i].getValue().indexOf(";") + 1));
 46 
 47     }
 48 
 49    }
 50 
 51   } catch (Exception e) {
 52 
 53    e.printStackTrace();
 54 
 55   }
 56 
 57  
 58 
 59   System.out.println(ssoCookies.toString());
 60 
 61   System.out.println("=========================================");
 62 
 63  
 64 
 65   // 2.get请求需要重定向
 66 
 67   redirectUrl = redirectUrl + redirectParams;
 68 
 69   RequestConfig redirectConfig = RequestConfig.custom().setRedirectsEnabled(true).build();// 允许重定向
 70 
 71   CloseableHttpClient redirectHttpClient = HttpClients.custom().setDefaultRequestConfig(redirectConfig).build();
 72 
 73   HttpClientContext redirectContext = HttpClientContext.create();
 74 
 75  
 76 
 77   HttpGet redirectHttpGet = new HttpGet(redirectUrl);
 78 
 79   redirectHttpGet.setHeader("Cookie", ssoCookies.toString());
 80 
 81  
 82 
 83   try {
 84 
 85    CloseableHttpResponse redirectResponse = redirectHttpClient.execute(redirectHttpGet, redirectContext);
 86 
 87    List redirectLocations = redirectContext.getRedirectLocations();
 88 
 89    for (URI item : redirectLocations) {
 90 
 91     System.out.println(item.toString());
 92 
 93    }
 94 
 95  
 96 
 97   } catch (ClientProtocolException e2) {
 98 
 99    e2.printStackTrace();
100 
101   } catch (IOException e2) {
102 
103    e2.printStackTrace();
104 
105   }
106 
107  }
108 
109  
110 
111 }

 

转载于:https://www.cnblogs.com/feng123/p/9449888.html

你可能感兴趣的:(HttpClient4.5 SSO登录)