卷曲到java Rest客户端Jersy

时间:2017-12-04 16:28:43

标签: java rest authentication curl

我正在使用需要身份验证的休息服务,使用了下面的curl命令来实现此目的

curl -v --insecure --request POST" https://ip:port/login" -d IDToken1 ="用户名" -d"密码" --cookie-jar cookie.txt

验证后,它会创建一个cookie文件。

有人可以帮助使用java创建相应的rest客户端。

我用过

ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);
    WebTarget target = client
            .target("http://hilweb05:8080/login");
    Form form = new Form().param("IDToken1", "username").param("IDToken2", "password");

    Response jsonAnswer = target.request()
            .accept(MediaType.APPLICATION_JSON).post(Entity.form(form));
    if (jsonAnswer.getStatus() != 200) {
        throw new RuntimeException("Not reachable "
                + jsonAnswer.getStatus());
    }
    List<SomeDataClass> matList = jsonAnswer.readEntity(new  GenericType<List<SomeDataClass>>() {});
    for (SomeDataClass m : matList) {
        System.out.println(m.getF1() + " " + m.getF2() + " "
        + m.getF3());
    }       

但它不起作用

2 个答案:

答案 0 :(得分:1)

我切换到Apache http客户端,使用下面的代码我可以获取cookie。

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    import javax.net.ssl.SSLContext;

    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.client.LaxRedirectStrategy;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.ssl.SSLContexts;
    import org.apache.http.util.EntityUtils;

    public class ApacheHttpClient {


    public static void main(String[] args) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial((chain, authType) -> true).build();

        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslContext, new String[]
                {"SSLv2Hello", "SSLv3", "TLSv1","TLSv1.1", "TLSv1.2" }, null,
                NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
         try {

             HttpPost httpPost = new HttpPost("url/login");
             List <NameValuePair> nvps = new ArrayList <NameValuePair>();
             nvps.add(new BasicNameValuePair("IDToken1", name));
             nvps.add(new BasicNameValuePair("IDToken2", password));
             httpPost.setEntity(new UrlEncodedFormEntity(nvps));
             CloseableHttpResponse response2 = httpclient.execute(httpPost);

             try {
                 System.out.println("Status -->>> "+ response2.getStatusLine().getStatusCode());

                 Header[] cookieInf = response2.getHeaders("Set-Cookie");
                 StringBuilder strBf = new StringBuilder();
                 for(Header header : cookieInf)
                 {
                     strBf.append(header.getValue());
                 }
                 System.out.println("Data is "+ strBf);
                 HttpEntity entity2 = response2.getEntity();


                 // do something useful with the response body
                 // and ensure it is fully consumed
                 EntityUtils.consume(entity2);

             } finally {
                 response2.close();
             }
         } finally {
             httpclient.close();
         }
    }

    }

现在我需要在文本文件中编写cookie,因此我需要帮助解析cookie信息,以便它与curl命令生成的cookie文件匹配。

答案 1 :(得分:0)

使用以下代码可以正常工作

public class JerseyClientPost {

    public static void main(String[] args) {
        try {


            Client client = Client.create(configureClient());
            final com.sun.jersey.api.client.WebResource webResource = client
                    .resource("https://wtc2e3enm.eng.mobilephone.net:443/login");
            MultivaluedMap formData = new MultivaluedMapImpl();
            formData.add("IDToken1", name);
            formData.add("IDToken2", password);
            try {
                ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED)
                        .accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, formData);



                String x = response.getEntity(String.class);
                System.out.println("Response String is "+ x);
            } catch (com.sun.jersey.api.client.ClientHandlerException che) {
                che.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ClientConfig configureClient() {
        TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
        } };
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        } catch (java.security.GeneralSecurityException ex) {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

        ClientConfig config = new DefaultClientConfig();
        try {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(new HostnameVerifier() {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    }, ctx));
        } catch (Exception e) {
        }

        return config;
    }
}

但我无法从响应中获取cookie,如果我使用curl,我可以使用--cookie-jar参数获取cookie。有人可以帮助获取cookie