Post request with basic auth in retrofit? - java

Using Retrofit I post my contact list on the phone without authentication. I need to do retrofit basic authentication, but as far as I can't see from the internet. Can you help me, please?
This is my Code:
public void GetContactsIntoArrayList(){
mAPIService = ApiUtils.getAPIService();
final User user = new User();
final Post post = new Post();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
int i = 0;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
user.setphoneNumber(phonenumber.toString().trim());
user.setname(name.toString().trim());
List<User> phoneList = new ArrayList<>();
phoneList.add(user);
post.setUsers(phoneList);
sendPost(post);
}
cursor.close();
}
public void sendPost(Post post){
mAPIService.savePost(post).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
Log.i("Is Ok?","OK :)");
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}

This is so far the easiest method i have ever tried for "Basic Authentication".
Use the below code to generate the auth header (API/Repository class)
var basic = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD")
Pass this as header to the webservice call (API/Repository class)
var retrofitCall = myWebservice.getNewsFeed(basic)
Add the basic header as parameter (Retrofit Webservice interface class)
#GET("newsfeed/daily")
fun getNewsFeed(#Header("Authorization") h1:String):Call<NewsFeedResponse>
My code is in Kotlin, just in case you were looking for Java. But can be easily translated to Java.
References: https://mobikul.com/basic-authentication-retrofit-android/

You can add auth value in header of the request like if you want to send auth token then follow below step:
#POST("/auth/update-contactno")
#Headers(
"Content-Type: application/json",
Constants.headerApp,
Constants.headerLanguage,
Constants.headerPlatform,
Constants.headerVersion
)
fun updateMobileNumber(#Header(Constants.authorization) token: String?, #Body verifyForgotPasswordOTPInput: VerifyForgotPasswordOTPInput): Call<JsonObjectResponse<UserModel>>
And call updateMobileNumber() like :
apiService.updateMobileNumber(token, verifyForgotPasswordOTPInput)

Related

How to send a voice call to multiple people with Java and Twilio

I have this method, that makes the request to the specified phone number:
public Call sendVoiceCall(String responsiblePhoneNumber, String completeName) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
String helloTwiml = new VoiceResponse.Builder()
.say(new Say.Builder("Whatever")
.voice(Say.Voice.ALICE).language(Say.Language.PT_BR).build())
.build().toXml();
Call call = Call.creator(
new PhoneNumber(responsiblePhoneNumber),
new PhoneNumber(twilioPhoneNumber),
new Twiml(helloTwiml))
.create();
return call;
}
I call it inside this method:
#PostMapping("/sendVoiceCall")
#Transactional
#Async
public void sendVoiceCall() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Optional<User> username = userRepository.findByUsername(auth.getName());
List<Dependency> uuids = dependencyRepository.returnAllContactUuid(username.orElse(null).getUuid());
uuids.forEach(contact -> {
Optional<User> user = userRepository.findByUuid(contact.getContactUuid());
voiceCallService.sendVoiceCall(user.orElse(null).getPhone(), username.get().getCompleteName());
});
log.info("There was a request to warn users responsible for: " + username.orElse(null).getCompleteName());
}
When I try to send just to one person it works, but when I try to iterate using lambda, it gives me a 200 code and makes nothing.
Thanks for your help!

whenever i acces data from network using retrofit it works fine but in 2nd time can't find data through network using retrofit

I am trying to access data from the network (data is in the form of gson and i am using WordPress rest API) using retrofit but can't access. it shows me an error like data is null looks like retrofit can't find data but everything is good... looks like code is good and i don't know how to solve this. please help me I am a new developer.. it takes my 3 days
whenever i call getRetrofit() method it works fine... but when i call getImageRetrofit() then looks like this method won't work...this method return null value as shown in the logcat :
ImageInfo: info: null
private void getRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
Call<List<WPPost>> call = service.getPostInfo();
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.e("Latest","response: "+response.body());
for (int i=0; i<response.body().size(); i++)
{
Log.e("main ","title "+response.body().get(i).getTitle().getRendered() + " " +
response.body().get(i).getId() );
String tempDate = response.body().get(i).getDate();
tempDate = tempDate.replace("T"," ");
String tempImageHref = response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref();
Log.e("Href", "onResponse: "+tempImageHref);
String link = response.body().get(i).getLink();
Log.e("PostLink",link);
getImageRetrofit(tempImageHref);
list.add(new LatestModel(
response.body().get(i).getTitle().getRendered(),
tempDate,
tempImageHref,
LatestModel.IMAGE_TYPE,
response.body().get(i).getLink()
)
);
}
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
t.printStackTrace();
}
});
}
private void getImageRetrofit(String ImageHref) {
Log.e("getImageRetrofit","called "+ImageHref);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
Call<List<WPPostImage>> callImage = service.getImageInfo(ImageHref);
callImage.enqueue(new Callback<List<WPPostImage>>() {
#Override
public void onResponse(Call<List<WPPostImage>> call, Response<List<WPPostImage>> response) {
Log.e("ImageInfo","info: "+response.body());
}
#Override
public void onFailure(Call<List<WPPostImage>> call, Throwable t) {
Log.e("Link Failed: ",": t.printStackTrace()" );
}
});
}
here is my RetrofitArrayApi Interface.:
public interface RetrofitArrayApi {
#GET("wp-json/wp/v2/posts?per_page=4")
Call<List<WPPost>> getPostInfo();
#GET("{id}")
Call<List<WPPostImage>> getImageInfo(#Path("id") String ImageHref); }
You said at comments that temImageHref: mubashirsaddique.com/wp-json/wp/v2/media/1780 and also your base url is baseUrl = "mubashirsaddique.com". So you send a request to this address mubashirsaddique.com/mubashirsaddique.com/wp-json/wp/v2/media/1780 when call getImageInfo.
Change your getPostInfo service. It should return just id(1780 in your case) as href value and modify RetrofitArrayApi.
#GET("wp-json/wp/v2/media/{id}")
Call<List<WPPostImage>> getImageInfo(#Path("id") String ImageHref);

Retrofit2 JSON response body not parsed correctly

I'm having problems implementing a custom class as response JSON in Retrofit2.
The call succeeds and when I log the body (using HttpLoggingInterceptor) I can see the JSON is fetched correctly.
The only problem is that it is not parsed into the custom class I created.
Here is my ServiceGenerator:
public class ServiceGenerator
{
//Base url for the API
public static final String API_BASE_URL = "http://base.url";
private static Retrofit.Builder GSONBuilder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <T> T createJSONService(Class<T> serviceClass)
{
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
Retrofit retrofit = GSONBuilder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
Here is the ServiceInterface:
public interface ServiceInterface
{
class UserResponse
{
public int id;
public String email;
public String created_at;
#Override
public String toString()
{
return "UserResponse{" +
"id: " + id +
", email: " + email +
", created_at: " + created_at +
"}";
}
}
#GET("user/{userId}")
Call<UserResponse> currentUser(#Path("userId") int userId);
}
And this is where I actually call it:
public void getUser(int userId)
{
ServiceInterface clientCreate = ServiceGenerator.createJSONService(ServiceInterface.class);
Call<ServiceInterface.UserResponse> callCreate = clientCreate.currentUser(userId);
callCreate.enqueue(new Callback<ServiceInterface.UserResponse>()
{
#Override
public void onResponse(Call<ServiceInterface.UserResponse> call, Response<ServiceInterface.UserResponse> response)
{
ServiceInterface.UserResponse user = response.body();
if (user == null)
{
System.out.println("error");
}
else
{
System.out.println(user.toString());
//This line gets printed, but the class is empty
//What it should show: UserResponse{id: 5, email: "test#email.com", created_at: "2016-03-02"}
//What it actually shows: UserResponse{id: 0, email: null, created_at: null}
}
}
#Override
public void onFailure(Call<ServiceInterface.UserResponse> call, Throwable t)
{
System.out.println("Fail: " + t.getMessage());
}
});
}
I feel like I did everything right, is there any explanation why the GsonConverter does not convert the response to my custom class (UserResponse)?
To make myself even more clear, here is the actual JSON response (using Postman):
{"id": 5, "email": "test#email.com", "created_at": "2016-03-02"}
Thanks in advance!
Edit 1:
For anyone interested.
I have just figured out that if I use a String as a return type it actually writes all the data to the String.
So that means the fault lies with the conversion. I think that somewhere along the way I made a mistake with the GSONBuilder.

Can't get json response with Retrofit

I'm using retrofit 1.9.0 and I had tried the following code to get a response in json format:
public void Execute(String email, String password, Callback<User> callback) {
final Callback<User> cb = callback;
RestAdapter restAdapter = buildRestAdapter();
System.out.println("Email " + email + " passowrd " + password);
User user = new User();
user.setEmail(email);
user.setPassword(password);
restAdapter.create(YutonAPI.class).postLogin(
user,
new Callback<User>() {
#Override
public void success(User user, Response response) {
System.out.println("succes");
System.out.println(response.getBody());
}
#Override
public void failure(RetrofitError error) {
System.out.println("error "+ error);
}
});
}
So this line of code:
System.out.println(response.getBody());
Should give me a response in json format however it didn't work because I'm getting the following output:
Link: http://i.imgur.com/mBQs1LL.png
So this is how my response in json format should look like:
{
"user": {
"image": "https://www.gravatar.com/avatar/e0a190604dc3dd2ee7b66bb95c20ef7f?d=identicon&s=512"
"email": "a#hotmail.com"
"name": "a"
"id": "566dfac21043a31820bf1ae6"
} -
}
I had already tested it on my server where I was making a post request. Below you can see a screenshot of it:
Link: http://i.imgur.com/PtEMR12.png
The issue here is that response.getBody() returns a TypedInputStream object, which you can't directly output because it isn't a String.
To read a TypedInputStream there are several options, as posted in: Retrofit callback get response body, the easiest being:
String body = new String(((TypedByteArray) response.getBody()).getBytes());
If the following error is thrown:
java.lang.ClassCastException: retrofit.client.UrlConnectionClient$TypedInputStream cannot be cast to retrofit.mime.TypedByteArray
Then make sure that you set .setLogLevel(RestAdapter.LogLevel.FULL) on the RestAdapter that you use to create the service.

I got userinfo, how get user posts from wall?

I started work with Vkontakte android SDK, and doing it well). I made authorization, and got userFirstName, userLastName and userPhoto. But I have no idea how get user wall, or user posts from user wall. It should be similar, and I see response #2 in logcat, but I don't really know how parse it???
//Prepare request for userName and photo
final VKRequest request1 = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "photo_100, contacts"));
//Prepare request for userWall
final VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID));
//Parallel executing requests
VKBatchRequest batch = new VKBatchRequest(request1, request2);
batch.executeWithListener(new VKBatchRequest.VKBatchRequestListener() {
#Override
public void onComplete(VKResponse[] responses) {
super.onComplete(responses);
//Work with responses
//*****
//UserName and photo response
//*****
VKApiUserFull user = ((VKList<VKApiUserFull>) responses[0].parsedModel).get(0);
Ion.with(ivUserPhoto).placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.load(user.photo_100);
tvUserName.setText(user.first_name + " " + user.last_name);
//********
//Wall response similar sa userResponse...
//********
VKApiPost mPost = ((VKList<VKApiPost>) responses[1].parsedModel).get(0);
Log.e("post name", mPost.toString());
}
#Override
public void onError(VKError error) {
//Error;
}
});
Here right code, tnx Dreddik <-- vk android sdk developer.
VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, VKSdk.getAccessToken().userId, VKApiConst.EXTENDED, 1));
request2.executeWithListener(new VKRequestListener() {
#Override
public void onError(VKError error) {
}
#Override
public void onComplete(VKResponse response) {
VKList<VKApiPost> posts = (VKList<VKApiPost>) response.parsedModel;
VKApiPost post = posts.get(0);
Log.d("Post:", post.toString());
}
});

Categories

Resources