How to pass Authorization Bearer using retrofit? - android

Here I need to pass Authorization Bearer to get response from server in case of uploading file to server I am using retrofit.
I tried in two ways
1)
This is how I initialized in retrofit interface class
#POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(#Header("Authorization")String token, #Body UploadKycRequest uploadKycRequest);
This is how I called it from interface class
Call<UploadKycpojo> request = RestClient.getInstance(UploadIdActivtiy.this).get().uploadkycdoc("Bearer "+auth,uploadKycRequest);
2)
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(newRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(/** your url **/)
.addConverterFactory(GsonConverterFactory.create())
.build();
Any help will be appreciated.
Thanks in Advance!

You just need to add space before Bearer it's work for me try it:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", " Bearer " + token)
.build();
return chain.proceed(newRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(/** your url **/)
.addConverterFactory(GsonConverterFactory.create())
.build();

Your retrofit interface method should be like this:-
#Multipart
#POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(#Header("Authorization")String token, #Part
MultipartBody.Part file);
And your calling statement would be like this:-
File file = new File(yourStringPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));
MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
Call<UploadKycpojo> request = RestClient.getInstance(UploadIdActivtiy.this).get()
.uploadkycdoc("Bearer "+auth,multipartBody );

I did try and it's working for me please refer below code:
#Multipart
#POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(#Header("Authorization")String token, #Part
MultipartBody.Part file, #PartMap() Map<String,
RequestBody> partMap);
And for API call use below method:
private void uploadkycdoc() {
MultipartBody.Part filePart;
HashMap<String, RequestBody> requestBodyMap = new HashMap<>();
requestBodyMap.put("imageSlide", RequestBody.create(MediaType.parse("multipart/form-data"), "front"));
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<UploadKycpojo> uploadkycdocCall = null;
File file = new File(getRealPathFromURI(fileUri, context));
RequestBody requestFile = RequestBody.create(MediaType.parse("*/*"), file);
filePart= MultipartBody.Part.createFormData("file", file.getName(),
requestFile);
uploadkycdocCall = apiInterface.uploadkycdoc("Bearer " + token, filePart, requestBodyMap);
uploadkycdocCall.enqueue(new Callback<UploadKycpojo>() {
#Override
public void onResponse(Call<UploadKycpojo> call, Response<UploadKycpojo> response) {
cancelProgressDialog();
try {
if (response.isSuccessful()) {
} else {
}
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<UploadKycpojo> call, Throwable t) {
}
});
}

Kotlin Ex:
retrofit Get request with AUTH HEADER
#GET("api-shipping/Apps")
fun getApp(#Header("Authorization") auth: String) : retrofit2.Call<JsonObject>
call enqueue don't forget to add Bearer with a space in tokken
val tokken = "Bearer TOKKEN_Key"
call.enqueue(object : Callback<JsonObject> {
override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
}
override fun onFailure(call: Call<JsonObject>, t: Throwable) {
}
})
}

Related

Posting and image using Okhttp to Django Rest Frame work Back end

I have a back end that I am able to upload a file to it by the following request in Pyhton:
data = {
"prop_post": 35
}
headers = {
# "Content-Type": "application/json",
"Authorization": "JWT " + t1,
}
if img_path is not None:
with open(img_path, 'rb') as image:
file_data = {
'photo': image
}
r = requests.post(POSTS_ENDPOINT, data=data,files=file_data, headers=headers)
that is my development environment. Now in production I am going to use Android as client to upload image. I am using Okhttp3. Here is the code that I am using to upload an image:
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
String file2 = utils.getRealPathFromURI2(obj.getPhotos_uri()[0], context);
File file = new File(file2);
RequestBody req = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("prop-post", Integer.toString(id))
.addFormDataPart("photo", "IMG-20190705-WA0002.jpg",
// RequestBody.create(MEDIA_TYPE_PNG, file.getAbsolutePath())).build();
RequestBody.create(MEDIA_TYPE_PNG, file)).build();
Request request = new Request.Builder()
.url(root + "images/")
.addHeader("Authorization", header)
.post(req)
.build();
OkHttpClient client = new OkHttpClient();
Response response2 = client.newCall(request).execute();
This request doesn't go through with 400 (Bad request) response. My file absolute location in Android is : /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20190705-WA0002.jpg
I appreciate if some one can tell me what I am doing wrong.
Thanks in advance
I ended up using retrofit:
added these dependencies in gradle:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
then defined the following interface:
public interface ImageAPI {
#Multipart
#POST("images/")
Call<ResponseBody> createPost( #Part MultipartBody.Part file, #Part("prop_post") RequestBody requestBody);
}
then my post call looks like this:
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().header("Authorization", "mytoken");
return chain.proceed(newRequest.build());
}
});
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(rootUrl)
.client(okHttpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ImageAPI imageAPI = retrofit.create(ImageAPI.class);
String image_path = imagepath;//sets when browsing image
File file = new File(image_path);
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("photo", file.getName(), fileReqBody);
RequestBody id= RequestBody.create(MediaType.parse("text/plain"), "68");
Call<ResponseBody> call = imageAPI.createPost(part, id);
try {
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("tag", "onResponse: " + response.message().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("tag", "onResponse: " + t.getMessage());
}
});
} catch (Exception e) {
Log.d("tag", "onCreate: " + e.getMessage());
}

Retrofit Post Request With Form data

I am new to android .
I want to upload image as form data using Retrofit Post method.
I am using com.squareup.retrofit2:retrofit:2.3.0
This is my request body.
**Make interface like this add "MultipartBody.Part" in request and set your image path as post method and you can upload image using retrofit use this networkclient class to create retrofit instance **
public class NetworkClient {
private static final String BASE_URL = "";
private static Retrofit retrofit;
public static Retrofit getRetrofitClient(Context context) {
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface UploadAPIs {
#Multipart
#POST("/upload")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part file, #Part("name") RequestBody requestBody);
}
private void uploadToServer(String filePath) {
Retrofit retrofit = NetworkClient.getRetrofitClient(this);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
//Create a file object using file path
File file = new File(filePath);
// Create a request body with file and image media type
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
// Create MultipartBody.Part using file request-body,file name and part name
MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
//Create request body with text description and text media type
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
//
Call call = uploadAPIs.uploadImage(part, description);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
}
#Override
public void onFailure(Call call, Throwable t) {
}
});
}
Try this
#Multipart
#POST(Global.updateProfilePicture)
Call<YOUR_RESPONSE_MODEL> updatePicture(#Header("Authorization") String authorization, #PartMap Map<String, RequestBody> params);
And API call should be like this
public void updatePic(String senderID, String receiverID, String type, File photo) {
mProgressDialog.show();
final Map<String, RequestBody> map = new HashMap<>();
try {
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), photo);
map.put("image\"; filename=\"" + photo.getName() + "\"", fileBody);
} catch (Exception e) {
e.printStackTrace();
}
map.put("sender_id", RequestBody.create(MediaType.parse("multipart/form-data"), senderID));
map.put("receiver_id", RequestBody.create(MediaType.parse("multipart/form-data"), receiverID));
map.put("type", RequestBody.create(MediaType.parse("multipart/form-data"), type));
Call<YOUR_RESPONSE_MODEL> call = mApiInterface.updatePicture(ACCESS_TOKEN, map);
call.enqueue(new Callback<YOUR_RESPONSE_MODEL>() {
#Override
public void onResponse(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Response<YOUR_RESPONSE_MODEL> response) {
if (mContext != null) {
mProgressDialog.dismiss();
// Dismiss Dialog
}
}
#Override
public void onFailure(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Throwable t) {
if (mContext != null) {
mProgressDialog.dismiss();
}
}
});
}
I got output by doing request as following
UploadAPI Interface
`
#Multipart
#Headers({"TOKEN:XXXX"})
#POST("/api/messages/image")Call<ImageResult>uploadImage(#Part("sender_id")RequestBody sender_id,#Part("receiver_id")RequestBody receiver_id,#Part("type")RequestBody type,#Part MultipartBody.Part image);`
And Following is Method Code, I tried
`
private void uploadToServer(String filePath)
{
Retrofit retrofit = NetworkClient.getRetrofitClient(this, sendImageMsgURL);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
File file = new File(filePath);
MultipartBody.Part requestImage = null;
RequestBody requestFile = RequestBody.create(MediaType.parse("mutlipart/form-
data"),file);
requestImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
RequestBody sender_id = RequestBody.create(MediaType.parse("multipart/form-data"),
currentID);
RequestBody receiver_id = RequestBody.create(MediaType.parse("multipart/form-data"),
otherID);
RequestBody type = RequestBody.create(MediaType.parse("multipart/form-data"), "image");
Call<ImageResult> call = uploadAPIs.uploadImage(sender_id, receiver_id, type,
requestImage);
call.enqueue(new Callback<ImageResult>()
{
private Call<ImageResult> call;
private Response<ImageResult> response;
#Override
public void onResponse(Call<ImageResult> call, Response<ImageResult> response)
{
this.call = call;
this.response = response;
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("Error--------- :", t.getMessage());
}
});
}`

Error in make post reques using RETROFIT

I have a problem in using retrofit. I have a API https://raakar.ir/addProject and want to send some information. API works fine in postman. I want to make post request. I think, I do every think correctly. But when I run the app, It crash.
I used these libraries:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
and these are my interface of retrofit :
public interface APIInterface {
#Multipart
#POST("addProject")
Call<AddProjectResponse> post(
#Header("token") String token,
#Field("name") String name,
#Field("amount") String amount,
#Field("description") String description,
#Field("category") String category,
#Field("deadline") String deadline,
#Field("projectFile")Bitmap bitmap
);
}
------------------------------------------------------------------------------------------------------------------------------------
Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl("https://raakar.ir/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
APIinterface retroInterface = retrofit.create(APIinterface.class);
Call<AddProjectResponse> call = retroInterface.post(token,
"طراحی راکار",
"50000000",
"خالی است",
"برنامه نویسی",
"5",
null);
call.enqueue(new Callback<AddProjectResponse>() {
#Override
public void onResponse(Call<AddProjectResponse> call, Response<AddProjectResponse> response) {
Log.d("Resposne:", response.toString());
}
#Override
public void onFailure(Call<AddProjectResponse> call, Throwable t) {
Log.d("Respone:", "Error");
}
});
PLEASE HELP me!
i thing if you are not post any image and other file like video etc then you can not used #Multipart and also pass in post method paremater make one pojo class for that and only pass your object like below that...sample code
MyEventRequestModel myEventListRequestModel = new MyEventRequestModel(); // define your pojo class object
myEventListRequestModel.setDate(mDate);
Call<MyEventResponseModel> call = apiInterface.getAllEvent(myEventListRequestModel);
and header will be set on retrofit intialized..
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, "")) // hear define your header.
.build();
}
return chain.proceed(request);
}
});
If You use #Multipart than use #Part not #Field
public interface APIInterface {
#Multipart
#POST("addProject")
Call<AddProjectResponse> post(
#Part ("token") String token,
#Part ("name") String name,
#Part ("amount") String amount,
#Part ("description") String description,
#Part ("category") String category,
#Part ("deadline") String deadline,
#Part MultipartBody.Part img
);
}

How to send Token in Header to server in Android

In my application I want to create a Login/Register page.
In the login page I send the Username, Password, Token from client to Server.
I should get Username and Password from USER, and get Token from HEADER of Request.
For connect client to server I use Retorfit 2.2.0 library.
Code from the Interface class :
#POST("User/Authenticate")
Call<LoginResponse> getLoginResponse(#Header("Token") String token, #Body LoginDatum loginDatum);
Code within the Activity :
public void getLogin(String username, String password) {
final LoginDatum loginDatum = new LoginDatum();
loginDatum.setUsername(username);
loginDatum.setPassword(password);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum);
Log.e("tokenTAG", "Token : " + sendToken);
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
String token = response.headers().get("Token");
if (token != null) {
sendToken = token;
Log.e("tokenTAG", "Token : " + sendToken);
}
if (loginResponse.getStatusCode() == 200) {
Toasty.success(context, context.getResources().getString(R.string.welcome) + " " +
loginResponse.getData().getName(), Toast.LENGTH_LONG, true).show();
} else {
Toasty.error(context, loginResponse.getStatusMessage() + "", Toast.LENGTH_LONG, true).show();
}
loadProgress.get(0).setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
btnShadow.setVisibility(View.VISIBLE);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
loadProgress.get(0).setVisibility(View.GONE);
loginBtn.setVisibility(View.VISIBLE);
btnShadow.setVisibility(View.VISIBLE);
Toasty.error(context, context.getResources().getString(R.string.failRequest),
Toast.LENGTH_LONG, true).show();
}
});
}
And show me this in LogCat :
tokenTAG: Token : null
tokenTAG: Token : MKGKFPOVRMU4MRK0STNDO20RA2MPEWT7Y1N2WUM5QLIXJX2TEOM9APGUTYJMD8R42WFVESD8GRXCTCINA2LZKU7JV2I7KA2R4N5W
But when I want to send the token with this code : Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum); it shows me null.
I have use this line : Call<LoginResponse> call = api.getLoginResponse(sendToken, loginDatum); to generate the request callBack, although this line Token is not NUll.
How can I fix it?
if you use Retrifit get onNetwork request,in order to add Header to your requese,you must be write an Intercepter.
just replace getClient menthod with this one
public static Retrofit getClient(final Context context) {
if (retrofit == null) {
Log.d("AuthTokenTest", "getClient: null");
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
dispatcher = new Dispatcher();
httpClient.dispatcher(dispatcher);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Log.d("INTERCEPTOR", original.url().toString());
//System.out.print(original.toString());
Request request;
user=User.getLoggedInUserInstance(context);
String authToken="";
if(user!=null)
authToken=user.getAuthToken();
Log.d("AuthTokenTest", "intercept: authtoken:"+authToken);
request = original.newBuilder()
.header("X-AUTH-TOKEN", authToken)
.header("x-requested-with", "XMLHttpRequest")
.method(original.method(), original.body())
.build();
okhttp3.Response response = chain.proceed(request);
Log.d("INTERCEPTOR-", "response_code: "+response.code());
// Log.d("INTERCEPTOR", response.body().string());
return response;
}
});
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
//print the logs in this case
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else{
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
httpClient.addInterceptor(loggingInterceptor);
OkHttpClient client = httpClient.build();
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
let me know if this solution works or not

retrofit2 upload file

I'm trying to upload a videofile from my app.
Here's what I've got so far:
public class Download extends Application {
public interface upload {
#Multipart
#POST("new")
Call<Response> send(#Part("myFile") RequestBody file);
}
public void uploadFile(File xfile) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.3")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestBody file = RequestBody.create(MediaType.parse("video/*"), xfile);
upload xUpload = retrofit.create(upload.class);
Call<Response> call = xUpload.send(file);
try {
Response result = call.execute().body();
}
catch (IOException e)
{
Log.d("TEST3", " didn't work ");
}
}
}
I get the following error retrofit2.Response' is not a valid response body type. Did you mean ResponseBody? for method upload.send any ideas
I've read up on the retrofit2 webpage and tried the main example they have for uploading a file but it didn't work for two reasons.
1. I couldn't find right ServiceGenerator
2. My file was found in the Gallery and I streamed its contents to a temporary file which I'm to upload, I can't access it directly from its URI... or can I with retrofit2?
i use to upload image from retrofit 2 like this,it worked correctly
File file = new File(image.getPath());
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("gallery", file.getName(), mFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), id);
final NetworkCall networkCall=new NetworkCall(this);
Call<ResponseBody> call = networkCall.getRetrofit(false).uploadImage( filename, fileToUpload);
call.clone().enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
here is my network call class:
public class NetworkCall {
Context context;
ProgressDialog progressDialog;
public NetworkCall(Context context){
this.context = context;
}
public IApi getRetrofit(boolean isShowLoading){
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectTimeout(0, TimeUnit.SECONDS).readTimeout(0,TimeUnit.SECONDS);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content_type","application/json")
.header("Accept", "application/json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
if (isShowLoading&&context instanceof BaseActivity)
showLoading();
// prepare call in Retrofit 2.0
IApi api = retrofit.create(IApi.class);
// Call<BaseResponce> call = api.callService(json);
//asynchronous call
// call.enqueue(this);
return api;
}
private void showLoading(){
try {
((BaseActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
public void dismissLoading(){
try {
((BaseActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.cancel();
progressDialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}
i use this in IApi class
#Multipart
#POST("events/file_upload.json")
Call <ResponseBody> uploadImage(#Part("event_id") RequestBody id,#Part MultipartBody.Part part);
hope it helps

Categories

Resources