Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Curl到javarest客户机Jersy_Java_Rest_Authentication_Curl - Fatal编程技术网

Curl到javarest客户机Jersy

Curl到javarest客户机Jersy,java,rest,authentication,curl,Java,Rest,Authentication,Curl,我正在使用一个需要身份验证的rest服务,下面使用curl命令来实现这一点 curl-v--不安全--请求发布“-d IDToken1=”用户名“-d”密码”-cookie jar cookie.txt 认证后,它会创建一个cookie文件 有人可以帮助使用java创建相应的rest客户机吗 我用过 ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config);

我正在使用一个需要身份验证的rest服务,下面使用curl命令来实现这一点

curl-v--不安全--请求发布“-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());
    }       
ClientConfig=newclientconfig();
Client Client=ClientBuilder.newClient(config);
WebTarget=client
.目标(”http://hilweb05:8080/login");
Form Form=new Form().param(“IDToken1”,“username”).param(“IDToken2”,“password”);
响应jsonAnswer=target.request()
.accept(MediaType.APPLICATION_JSON).post(Entity.form(form));
if(jsonAnswer.getStatus()!=200){
抛出新的RuntimeException(“不可访问”
+jsonAnswer.getStatus());
}
List matList=jsonAnswer.readEntity(新的GenericType(){});
对于(SomeDataClass m:matList){
System.out.println(m.getF1()+“”+m.getF2()+“”
+m.getF3());
}       

但是它不能用下面的代码工作

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吗?

我切换到ApacheHTTP客户端,通过下面的代码我可以获取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();
         }
    }

    }
import java.io.IOException;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.security.KeyManagementException;
导入java.security.KeyStoreException;
导入java.security.NoSuchAlgorithmException;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.List;
导入javax.net.ssl.SSLContext;
导入org.apache.http.Header;
导入org.apache.http.HttpEntity;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.CloseableHttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.conn.ssl.NoopHostnameVerifier;
导入org.apache.http.conn.ssl.SSLConnectionSocketFactory;
导入org.apache.http.impl.client.CloseableHttpClient;
导入org.apache.http.impl.client.HttpClients;
导入org.apache.http.impl.client.laxridirectstrategy;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.ssl.SSLContexts;
导入org.apache.http.util.EntityUtils;
公共类ApacheHttpClient{
publicstaticvoidmain(字符串[]args)抛出ClientProtocolException、IOException、KeyManagementException、nosuchagorithmexception、KeyStoreException{
SSLContext SSLContext=SSLContexts.custom()
.loadTrustMaterial((chain,authType)->true.build();
SSLConnectionSocketFactory SSLConnectionSocketFactory=
新的SSLConnectionSocketFactory(sslContext,新字符串[])
{“SSLv2Hello”、“SSLv3”、“TLSv1”、“TLSv1.1”、“TLSv1.2”},null,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient=HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
试一试{
HttpPost HttpPost=新的HttpPost(“url/登录”);
List-nvps=newarraylist();
添加(新的BasicNameValuePair(“IDToken1”,名称));
添加(新的BasicNameValuePair(“IDToken2”,密码));
setEntity(新的UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2=httpclient.execute(httpPost);
试一试{
System.out.println(“状态-->>>”+response2.getStatusLine().getStatusCode());
Header[]cookieInf=response2.getHeaders(“设置Cookie”);
StringBuilder strBf=新的StringBuilder();
for(标题:cookieInf)
{
追加(header.getValue());
}
System.out.println(“数据为”+strBf);
HttpEntity entity2=response2.getEntity();
//对响应体执行一些有用的操作
//并确保它被完全消耗
EntityUtils.consume(entity2);
}最后{
response2.close();
}
}最后{
httpclient.close();
}
}
}

现在,我需要在文本文件中写入cookie,因此我需要帮助解析cookie信息,使其与curl命令生成的cookie文件相匹配。

我使用了下面的代码来完成此操作,并且工作正常。我尝试了response.getHeaders().get(“set cookie”)和response.getCookies()和response.getHeaders().values()但是什么都没有