繁体   English   中英

如何在改造中使用基本身份验证发送帖子请求?

[英]How to send post request with basic auth in retrofit?

在我的代码中,我想发送带有基本身份验证的 post 请求。

这是我的邮递员截图:

在此处输入图片说明

这是我的 apiInterface 类

@FormUrlEncoded
    @POST("GetBarcodeDetail")
    Call<PreliminaryGoodsAcceptResponse> PRELIMINARY_GOODS_ACCEPT_RESPONSE_CALL(@Field("ProcName") String procName, @Field("Barcode") String barcode, @Field("LangCode") String langCode);

这是我的 apiclient

public class ApiClient {

    public static final String BASE_URL = "http://192.**********";
    private static Retrofit retrofit = null;
    private static OkHttpClient sClient;

    public static Retrofit getClient() {
        if(sClient == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            sClient = new OkHttpClient.Builder()
                    .addInterceptor(new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT))
                    .addInterceptor(interceptor)
                    .build();
        }

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(sClient)
                    .build();
        }
        return retrofit;
    }

}

我的问题是如何使用标头发送发布请求:

标头用户名:EBA 令牌:
34242353453456563DSFS

这是迄今为止我为“基本身份验证”尝试过的最简单的方法。

使用以下代码生成身份验证标头(API/Repository 类)

 var basic = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD")

将此作为标头传递给 webservice 调用(API/Repository 类)

 var retrofitCall = myWebservice.getNewsFeed(basic)

添加基本​​头作为参数(Retrofit Webservice 接口类)

 @GET("newsfeed/daily")
 fun getNewsFeed(@Header("Authorization") h1:String):Call<NewsFeedResponse>

抱歉,我的代码使用 Kotlin,但可以轻松转换为 Java。

参考资料: https : //mobikul.com/basic-authentication-retrofit-android/

像这样制作标题..

 private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (context == null) {
                request = request
                        .newBuilder()
                        .build();
            } else {
                request = request
                        .newBuilder()
                        .addHeader("Authorization", "Bearer " + AppSetting.getStringSharedPref(context, Constants.USER_KEY_TOKEN, ""))
                        .build();
            }
            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

使用标题注释

@FormUrlEncoded
    @POST("GetBarcodeDetail")
    Call<PreliminaryGoodsAcceptResponse> PRELIMINARY_GOODS_ACCEPT_RESPONSE_CALL(@Header("Authorization") token: String,@Field("ProcName") String procName, @Field("Barcode") String barcode, @Field("LangCode") String langCode);

Simple-Retrofit-API-request-and-Data-Loading 这里我只添加了创建API调用以使用retrofit库访问数据库数据的项目; 这是领先的图书馆访问网络上的数据。 并以List格式显示访问的数据。 使用空活动创建简单的 Android Studio 项目。 创建适配器和活动项以在 android 应用程序中显示普通列表。 现在创建扩展 Application 的 App 类,因为 Application 类是一个单例,您可以从任何活动或任何其他有 Context 对象的地方访问它。 您可以从https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class查看有关 Application 类的更多详细信息为什么要扩展 Application 类? https://developer.android.com/reference/android/app/Application.html

添加android:name=".YourApplication",即扩展android 中的Application 类的类名。 和类将像公共类 YourApplication extends Application Init the Retrofit in Application 类

//network code start 
//init http logger  
httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// init client  client = new OkHttpClient.Builder()  
.addInterceptor(httpLoggingInterceptor)
 .addInterceptor(new Interceptor() {
  @Override public Response intercept(Chain chain) throws IOException {
   Request request = chain.request();
   Request request2 = request.newBuilder().build();
   return chain.proceed(request2);
  }
 }).connectTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
Gson gson = new GsonBuilder().setLenient().create();
Retrofit mRetrofit = new Retrofit.Builder().baseUrl(Constants.API_BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create(gson)).build();
mWebservice = mRetrofit.create(Webservice.class);

虽然 Constants.API_BASE_URL 是基本 url 创建 Webervice.class,您可以在其中使用参数调用 API,例如在 GET 方法的情况下:

@GET("webservices/GetAllClientsDemoRetro.php") 
Call updateChatStatus(); 

在 POST 方法的情况下:

@FormUrlEncoded  
@Headers({"Content-Type: application/x-www-form-urlencoded"})  
@POST("webservices/GetAllClientsDemoRetro.php")  

调用 updateChatStatus();
您可以在此处查看官方 API 声明中关于 Retrofit 的更多详细信息: http : //square.github.io/retrofit/
我们可以使用 Parceble 类通过 POJO 解析值,即 Setter 和 Getter。 由于解析键名应该等于我们从 JSON 响应中接收到的值。 POJO 类应该像公共类 ClientData 实现 Parcelable 一样声明,然后在类中声明键,键值意味着

public class ClientData implements Parcelable 
{  
public String client_id;  
public String company_name;  
public String address_line;  
public String city;  
public String pincode;  
public String state;  
public String country;  
}

现在使用 Alt+Enter,即选择 Add Parceble Implementation 选项并按 Enter。 然后将自动添加 parceble 类。 您还必须使用 Alt + Insert 在类中添加 Setter 和 Getter 方法。 注意:不要为 CREATER 添加 Setter 和 Getter 方法:Creater<> 方法如果要使用与 JSON 响应键不同的键,则应使用序列化。 当我使用相同的密钥时,它就像 public String client_id; 但是当我使用序列化时,我可以使用像@Serialization(“client_id”) public String ClientID; 现在最后但不是列表,我们使用改造调用 API,并使用响应查看列表中的项目 -

RetroFitApplication.getWebservice().updateChatStatus().enqueue(new Callback() {
 @Override public void onResponse(Call call, Response response) {
  Log.d("retrofilt success", "" + response.body());
  if (response.body() != null) {
   clientResponceData = response.body();
   Gson gson = new Gson();
   String body = gson.toJson(response.body());
   Log.d("retrofilt success2", "clientData" + clientResponceData.getResponse());
   if (clientResponceData.getResponse() != null) {
    initRV();
   }
  } else {
   // Empty Client List  Toast.makeText(ClientList.this, "Empty List", Toast.LENGTH_SHORT).show();  
  }
 }

 @Override public void onFailure(Call call, Throwable t) {
  Log.d("retrofilt error", "" + t);
  Toast.makeText(ClientList.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
 }
});

通过使用 Adapter 中的构造,我们可以使用响应中的值。 伙计们,我添加了这个存储库以获得调用 API 并使用 Retrofit 库从服务器获取响应的完整想法。 我用简单的词详细地写了整个​​文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM