在纯 java 中调用 rest 调用

Calling rest calls in pure java

我这里有一个小问题,我想进行 restfull post 调用,它的响应是一个带有会话 ID 的 cookie,然后我用一些不同的 url 并使用该 cookie 作为参考,否则如果我不使用该 cookie,我的 get 请求将被拒绝,因为我将不是授权用户,因此可以使用 curl 命令和命令轻松实现我正在使用

curl -X POST 'http://localhost:8465/myapp/j_spring_security_check?j_username=username&j_password=password' -v -c /tmp/localcookie.txt

curl -H "Content-Type: application/json" -X GET http://localhost:8465/myapp/entity/v1/loadLogs/3056 -b /tmp/ludwigcookie.txt > /tmp/somejson.json

如果您在上面的 curl 命令中看到我正在使用 post curl 创建 cookie 并使用该 cookie 我正在 运行ning get 请求我将结果存储在 json 文件中。所以,我的问题是,在普通 java 中调用 post 请求,然后从响应中创建一个 cookie,然后再次使用该 cookie 调用 Get 方法并从中创建 json 对象.我尝试使用 URL 和 httpURLconnection 但无法成功,我们将不胜感激。

curl -X POST 'http://localhost:8465/myapp/j_spring_security_check?j_username=username&j_password=password' -v -c /tmp/ravocookie.txt

* About to connect() to localhost port 8465 (#0)
*   Trying 192.168.1.0... connected
* Connected to localhost (192.168.1.0) port 8465 (#0)
> POST /myapp/j_spring_security_check?j_username=username&j_username=password HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.8 libidn/1.18 libssh2/1.4.2
> Host: localhost:8465
> Accept: */*
>
< HTTP/1.1 302 Found
< Server: Apache-Coyote/1.1
* Added cookie JSESSIONID="DE14689C230FED8866011A56EF84A489" for domain hdpdedge01.twcable.com, path /myapp/, expire 0
< Set-Cookie: JSESSIONID=DE14689C230FED8866011A56EF84A489; Path=/myapp/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Location: /myapp/login?error
< Content-Length: 0
< Date: Thu, 03 May 2018 20:42:01 GMT
<
* Connection #0 to host localhost left intact
* Closing connection #0

如果你看到上面那个,我在 txt 文件中成功生成了 cookie,文本文件中的结果如下所示

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_localhost FALSE   /myapp/ FALSE   0   JSESSIONID  E6830C2782DF4340D780EF8C9812B103

但是当我 运行 @shubham 提到的 java 代码时,它给了我一个普通的 html 代码而不是 jsession

Java 代码响应如下所示

Response Code:200
Response Message:OK
<!DOCTYPE html><html class="loginHtml" lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="description" content=""><meta name="author" content=""><link rel="shortcut icon" href="resources/assets/images/favicon.ico"><title>Podium - big data management</title><!-- Bootstrap core CSS --><link href="resources/assets/fonts/open-sans/stylesheet.css" rel="stylesheet" type="text/css"><link href="resources/assets/css/bootstrap.css" rel="stylesheet"><link href="resources/assets/themes/default/style.min.css"   rel="stylesheet"><!-- JQuery --><script type="text/javascript" language="javascript" src="resources/assets/js/jquery.min.js"></script><script type="text/javascript" language="javascript" src="resources/assets/js/bootstrap.min.js"></script><!-- AngularJS --><script type='text/javascript' src='resources/assets/lib/angular/angular.js'></script><script type="text/javascript">document.write("<script type='text/javascript' src='resources/assets/login/LoginController.js?v=" + Date.now() + "'><\/script>");</script><!--[if lt IE 9]>     <link href="resources/assets/css/ie8.css" rel="stylesheet" type="text/css"/>            <script src="resources/assets/js/3.7.0-html5shiv.js"></script>      <script src="resources/assets/js/1.4.2-respond.min.js"></script>      <script src="resources/assets/js/html5shim-html5.js"></script><![endif]--><!--[if lt IE 9]><script src="resources/assets/js/json3.js"></script><![endif]--><link rel="stylesheet" type="text/css" href="resources/assets/themes/default/newuistyle.css"></head><body class="login" xmlns:ng="http://angularjs.org" id="ng-app" ng-app="PodiumLogin"><div class="alert alert-danger pd-browser-message-login absolute" id="pd-browser-message" style="display:none;">    <strong>Your browser is not supported. Please update to the latest version.</strong></div><div class="alert alert-danger text-center absolute" id="registerLicense" role="alert" style="display:none">  <p><span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span> Invalid username and password!</p> <button type="button" class="btn btn-default pd-regm-btn" data-toggle="modal" data-target="#RegModal">Register</button></div><div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container">     <div class="navbar-header pull-left">           <a class="navbar-brand logo" alt="Podium Data logo">                <!--i class="icon-logo"></i-->              <i class="icon-podium-new-logo"></i>            </a>        </div>      <div class="pull-right pd-support-text">            <!-- request for podium account text -->            <p class="pd-login-text" id="requestNewActText"></p>            <!-- request for podium account text -->        </div>  </div></div><div id="LoginPage" ng-controller="LoginController" class="row">    <!-- Login Form --> <form id="loginForm" name="loginForm" role="form" class="form-signin" action="/podium/j_spring_security_check" method="post">       <!--h3 class="form-signin-heading">Login</h3-->                                                                     <div class="alert alert-danger" >                       <span class="glyphicon glyphicon-exclamation-sign"></span> Invalid username and password!                   </div>                                                          <div class="pd-login-box">          <span class="pd-login-uName"></span>            <input type="name" autofocus required placeholder="Username" ng-model="username" id="j_username_plain" class="form-control usr" ng-change="checkForAtSign()" ng-keypress="logMeIn($event)" aria-label="Username">       </div>      <div class="pd-login-box">          <span class="pd-login-pass icon-lock"></span>           <input type="password" required placeholder="Password" ng-model="password" name="j_password" class="form-control pwd" ng-keypress="logMeIn($event)" aria-label="Password">      </div>      <input type="hidden" placeholder="" id="podium_user_name" name="j_username" class="form-control">                   <div class="pd-getDomains-box" id="domainDropDown">         <!--label for="getDomains">Choose domain:</label-->             <select id="getDomains" class="pd-getDomains" ng-disabled="dropdownDisabled" ng-model="selectedDomain" ng-options="i.display for i in domains" aria-label="Choose Domain"></select>     </div>      <button type="button" class="btn btn-lg btn-primary btn-block btn-login" ng-click="submitLogin()"><!-- span class="glyphicon glyphicon-lock"></span --> Login </button>             <p></p>     <!-- p>         <span class="glyphicon glyphicon-question-sign"></span>  Can't access your account?     </p --> </form> <!-- Forget Password Form -->   <form role="form" class="form-signin" action="#source" style="display:none">        <h3 class="form-signin-heading">Forgot Password</h3>        <p>Enter the e-mail address you used to create your Podium account.</p>     <input type="email" autofocus required placeholder="Enter your Email" class="form-control">     <button type="submit" class="btn btn-lg btn-primary btn-block btn-login"><span class="glyphicon glyphicon-log-in"></span>  Submit</button>  </form> <!-- Email Sent --> <form role="form" class="form-signin" action="#source" style="display:none">        <h3 class="form-signin-heading">Please check your email</h3>        <p>We've sent you an email that will allow you to reset your password quickly and easily.</p>       <button type="submit" class="btn btn-lg btn-primary btn-block btn-login"><span class="glyphicon glyphicon-log-in"></span>  Continue</button>    </form></div><div id="RegisterPage" style="display:none">   <form role="form" class="form-signin" action="#">       <div class="pd-regModal-loginbox">          <!--h3 class="form-signin-heading">Register Key</h3-->          <textarea autofocus required class="form-control" placeholder="Register Key" id="licKeyString"></textarea>          <button type="button" class="btn btn-lg btn-primary btn-block btn-reglogin">Back</button>           <button type="button" class="btn btn-lg btn-primary btn-block btn-regRegister" onclick="registerLicense()"><span class="glyphicon glyphicon-lock "></span> Register</button>            <div class="alert pd-regLoginSuccess" id="notification-bar" style="display:none;"></div>        </div>  </form></div>     <script type="text/javascript">$(document).ready(function() { $('.pd-regm-btn').on('click',function() {      $('#LoginPage').hide();     $('#RegisterPage').show();      $('#registerLicense').hide();    }); $('.btn-reglogin').on('click',function() {     $('#RegisterPage').hide();      $('#registerLicense').hide();       $('#LoginPage').show();  }); // clearing local storage   localStorage.clear();});function registerLicense() {    var licKeyString = $("#licKeyString").val();    var licenseInfo = {"licKeyString" : licKeyString};/*    //grap host:port/app    var path = location.pathname.split('/');    if (path[path.length-1].indexOf('.html')>-1) {          path.length = path.length - 1;  }   var app = location.protocol + '//' + location.host + "/" +path[path.length-2]; // if you just want 'three'*/    $.ajax({        url: 'license/register',        type: 'put',        data: JSON.stringify(licenseInfo),      dataType: 'json',       contentType: 'application/json',        success: function(data) {           var message = "";           if(data.shortMessage !== undefined ) {                  message = data.shortMessage;                $('#notification-bar').removeClass('alert-success');                $('#notification-bar').addClass('alert-danger');                $('#notification-bar').show();            } else {              message = "License key registered successfully. Please Login to use Podium services.";              $('#notification-bar').removeClass('alert-danger');             $('#notification-bar').addClass('alert-success');               $('#notification-bar').show();            }             $('#notification-bar').html(message);       },          error: function(jqXHR, textStatus, errorThrown) {           var message = "<span class='glyphicon glyphicon-exclamation-sign'></span> Some error occurred while registering license key.";          $('#notification-bar').html(message);           $('#notification-bar').removeClass('alert-success');            $('#notification-bar').addClass('alert-danger');            $('#notification-bar').show();      }   });}//check Mozilla browser version function getMozillaVersion () { var raw = navigator.userAgent.match(/Firefox\/([0-9]+)\./); var currentVer = raw ? parseInt(raw[1]) : false;    if (currentVer < 41) {      $('#pd-browser-message').show();    }}//check Mozilla browser version //check chrome browser version function getChromeVersion () {         var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);    var currentVer = raw ? parseInt(raw[2], 10) : false;    if (currentVer < 45) {      $('#pd-browser-message').show();    }}//check chrome browser version //check opera browser version function getOperaVersion () {    var raw = navigator.userAgent.match(/OPR\/([0-9]+)\./); var currentVer = raw ? parseInt(raw[1]) : false;    if (currentVer < 32) {          $('#pd-browser-message').show();    }}//check opera browser version /* for ie */function getIEVersion() {   var sAgent = window.navigator.userAgent;    var Idx = sAgent.indexOf("MSIE");   // If IE, return version number.    if (Idx > 0) {      $('#pd-browser-message').show();        return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));    } else if (!!navigator.userAgent.match(/Trident\/7\./)) {       // If IE 11 then look for Updated user agent string.        $('#pd-browser-message').hide();        return 11;  } else {        return 0; //It is not IE    }}var chrome = navigator.userAgent.indexOf("Chrome") >= 0;var firefox = navigator.userAgent.indexOf("Firefox") >= 0;var opera = navigator.userAgent.indexOf("OPR") >= 0;var safari = navigator.userAgent.indexOf("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0;var ie = window.navigator.userAgent.indexOf("MSIE") >= 0;if(chrome) {   getChromeVersion();} else if(firefox) { getMozillaVersion();} else if(opera) {  getOperaVersion();} else if(ie) {   getIEVersion();}$(window).load(function(){  $.ajax({        url: 'license/getLoginInfo',        type: 'get',        success: function(data) {           var message = "";           if(data != null && data != undefined){                  if (data.trim() == ""){                     $("#requestNewActText").hide();                 } else {                    $("#requestNewActText").show();                     $("#requestNewActText").html(data);                     $('#notification-bar').hide();                 //   $('#supportCenter').attr("href","mailto:" + data);                  }           } else {                $("#requestNewActText").hide();             }       },          error: function(jqXHR, textStatus, errorThrown) {           var message = "<span class='glyphicon glyphicon-exclamation-sign'></span> Some error occurred while getting Podium contact detail.";            $('#notification-bar').html(message);           $('#notification-bar').removeClass('alert-success');            $('#notification-bar').addClass('alert-danger');            $('#notification-bar').show();      }   });})if(window.navigator.userAgent.indexOf("Trident") >= 0){    $("html").addClass("ie");   $("body").addClass("ie");}</script></body></html>

我通过这样做找到了完美的解决方案,

private static String getCookie(String userName, String password, String hostURL) {

    try {
        //Setting the url
        String url = hostURL + "/j_spring_security_check";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String USER_AGENT = "Mozilla/5.0";
        post.setHeader("User-Agent", USER_AGENT);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        //Seting the body parameters for post call.
        urlParameters.add(new BasicNameValuePair("j_username", userName));
        urlParameters.add(new BasicNameValuePair("j_password", password));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        //Get the cookies in a string
        Header[] headers = response.getHeaders("Set-Cookie");
        String cookie = null;
        for (Header h : headers) {
            cookie = h.getValue().toString();
        }
        //return the cookie.
        return cookie;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

    }

    return null;
}