【问题标题】:How to USE following CURL command in java?如何在 java 中使用以下 CURL 命令?
【发布时间】:2016-08-15 20:30:56
【问题描述】:

这是网址

curl -H "授权:承载 oVi4yPxk1bJ64Y2qOsLJ2D2ZlC3FpK4L" https://api.url.com/v1/market/total-items.json

我想在 JAVA 上使用它,其中 oVi4yPxk1bJ64Y2qOsLJ2D2ZlC3FpK4L 值将是我使用变量接收的动态值。

【问题讨论】:

  • Curl 是一个 bash 命令,您需要实现 GET 和/或 POST 来执行您的请求。您可以使用图书馆或自己做。看Retrofit或者Volley,有很好的库。
  • "Authorization: Bearer oVi4yPxk1bJ64Y2qOsLJ2D2ZlC3FpK4L" 添加到您的标题中。键是Authorization,值是Bearer oVi4yPxk1bJ64Y2qOsLJ2D2ZlC3FpK4L
  • 你能提供我的示例 php 代码吗?

标签: java android curl-commandline


【解决方案1】:

这就是你在 Java 中的做法。 curl - h 由 httpPost.addHeader() 处理 curl - d 由表单主体 curl -u 至少在这个 API(例如条带)的情况下,它是授权持有者。在 Oauth2 的情况下, curl -u 在标题中传递用户名:密码,例如

form.add(new BasicNameValuePair("username", request.getParameter("username")));

CloseableHttpClient userWebTokenHTTPclient;
        if (HIFIConstants.FULL_URL_HIFINITE.contains("localhost")) {  //for localhost HTTP request fails due to certificate issues, hence workaround. Works for Beta etc without SSLContext

            SSLContextBuilder sslcontext = new SSLContextBuilder();
            sslcontext.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            userWebTokenHTTPclient = HttpClients.custom().setSSLContext(sslcontext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();
        } else
            userWebTokenHTTPclient = HttpClients.createDefault();



        HttpPost httpPost = new HttpPost("https://api.somepublicsite.com/v1/ident/verits");

        List<NameValuePair> form = new ArrayList<>();
        form.add(new BasicNameValuePair("return_url", "https://example-dev.example.com?vi={VERIFICATION_INTENT_ID}"));
        form.add(new BasicNameValuePair("requested_verifications[0]", "identity_document"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);
        httpPost.setEntity(entity);

        httpPost.addHeader("Authorization", "Bearer somesecretkeyhere"); 
        httpPost.addHeader("Version", "v3");
        httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");    
        CloseableHttpResponse tokenResponse = userWebTokenHTTPclient.execute(httpPost);
        org.json.JSONObject verificationIntent = new org.json.JSONObject(EntityUtils.toString(tokenResponse.getEntity()));
        userWebTokenHTTPclient.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2019-09-18
    • 2018-02-10
    • 2018-07-14
    相关资源
    最近更新 更多