簡體   English   中英

卷曲到Java Rest客戶端Jersy

[英]Curl to java Rest client Jersy

我正在使用需要身份驗證的rest服務,下面的curl命令用於實現此目的

curl -v-不安全--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());
    }       

但是它不起作用

我切換到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文件匹配。

使用下面的代碼,它可以工作

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嗎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM