如何通过Retrofit发出CURL请求?

问题描述 投票:0回答:3

我正在尝试登录。

请求看起来像这样 $curl -u "username:PASSWORD" https://urlhere.com

如何使用改造使其发挥作用?

我尝试了授权标头,例如 request.addHeader("Authentication", username+":"+password);

请问有什么帮助吗?

android curl request retrofit
3个回答
6
投票

你的问题不够明确。 我想这是基本的身份验证,你可以使用这样的东西

@FormUrlEncoded
@POST("/login") void login(
        @Header("Authorization") String authorization,
        Callback<?> callback
);



// later when you call it

public static String getBase64String(String value) throws UnsupportedEncodingException {
    return Base64.encodeToString(value.getBytes("UTF-8"), Base64.NO_WRAP);
}

final String auth = "Basic " + getBase64String("user:password");
apiClient.login(auth, callback);

我希望有帮助。 :)


3
投票
  1. 如果您仅需要单独休息请求的使用授权,您可以通过@Header进行。可以使用@Header注释动态更新请求标头。

    @FormUrlEncoded
    @GET("/user")
    void getUser(@Header("Authorization") 
    String authorization, Callback<User> callback);
    

    哪里

    String authorization = "Basic " + getBase64String("user:password");
    

    例如,它将字符串:

    Basic b2QGdyb3Vwb24ucnU6aWxvdmVteW1hbWE=

    public static String getBase64String(String value) 抛出 UnsupportedEncodingException { 返回 Base64.encodeToString(value.getBytes("UTF-8"), Base64.NO_WRAP); }

  2. 如果您需要对所有其余请求使用授权,您可以通过Retrofit Interceptor添加@Header:

    new RestAdapter.Builder().
        setClient(...).
        setEndpoint(...).
        setErrorHandler(...).
        setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
               request.addHeader("Content-Type", "application/json");
               request.addHeader("Authorization", authorization);
               }
        }).
        build();
    

0
投票

要在拦截器中打印相当于 Retrofit 请求的 cURL 命令,您可以创建一个函数,该函数采用 RequestOptions 对象并从其属性构造 cURL 命令。然后您可以将此 cURL 命令打印到控制台。

以下是如何在 AppInterceptor 类中执行此操作的示例:

class AppInterceptor extends Interceptor {
  final _prefs = locator.get<SharedPreferenceHelper>();
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers["Content-Type"] = "application/json";
    options.headers["Authorization"] = "Bearer ${_prefs.getValues("token")}";
    print("cURL command: ${_buildCurlCommand(options)}");
    super.onRequest(options, handler);
  }

  String _buildCurlCommand(RequestOptions options) {
    final headers =
        options.headers.map((key, value) => MapEntry(key, "-H '$key: $value'"));
    final headerString = headers.values.join(' ');

    final method = options.method;
    final url = options.uri.toString();

    if (options.data != null) {
      final data = options.data;
      return "curl -X $method $headerString '$url' -d '$data'";
    } else {
      return "curl -X $method $headerString '$url'";
    }
  }
}`
© www.soinside.com 2019 - 2024. All rights reserved.