Post request to Firebase push notifications nothing happens - java

//Iam trying to do a post request for push notification, but nothing happens..
//The interface
interface RestInterface {
#Headers("Content-Type: application/json", "Authorization: key)
#POST("fcm/send")
fun sendingNotification(#Body body: NotificationBody?): Call<ResponseBody?>?
}
//NotificationBody
class NotificationBody(data: Data, to: String) {
#SerializedName("notification")
private val data: Data
#SerializedName("to")
private val to: String
init {
this.data = data
this.to = to
}
}
//Data class
class Data
(#field:SerializedName("title")
private val title: String,
#field:SerializedName("content")
private val content: String)
//Retrofit Request
fun sentNotification() {
val retrofit = Retrofit.Builder()
.baseUrl("https://fcm.googleapis.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
var title = "My Title";
var content = "My message";
var to = deviceId
var data = Data(title, content);
var body = NotificationBody(data, to);
val service = retrofit.create(RestInterface::class.java)
val response = service.sendingNotification(body)
i implemented response code but get a a lot of error. Remind, iam with kotlin not java.
response.enqueue( Callback<ResponseBody>() {
#Override
public void onResponse(retrofit2.Call<ResponseBody> call,
retrofit2.Response<ResponseBody> response) {
Log.d("kkkk","done");
}
#Override
public void onFailure(retrofit2.Call<ResponseBody> call,
Throwable t) {
}
})
}
//Whats wrong with above request setup ?
//if is sent the message with postman The notification is showing on the phone, so the onMessageReceived settings are ok

Related

Retrofit Post on Android kotlin not working but working on postman

I am trying to Hit the API using the Retrofit Post method to put the form data but the problem is that the API returns null all the time even if I try to pass the params. I tested the API by running it in Postman it works fine and I also added internet permission and set usesCleartextTraffic to true under manifest.xml, so it would be really helpful if anyone guides me to rectify this issue.
Output When I tried to debugg
call = Unresolved reference: call
response = Unresolved reference: response
this = {MainActivity#9661}
params = {HashMap#10022} size = 5
"password" -> "Ram#123"
"countryCode" -> {Integer#10042} 91
"name" -> "Ranjith"
"mobile" -> {Long#10046} 99********
"emailID" -> "var***#gmail.com"
Response back from the API with body null all the time
response = {Response#10220} "Response{protocol=http/1.1, code=400, message=Bad Request, url=http://*.***.***.***:***0/api/v1/****/auth/register}"
body = null
errorBody = {ResponseBody$1#10224}
content = {Buffer#10228} "[text={"code":400,"error":true,"msg":"Enter a valid name"}]"
contentLength = 52
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
uploadBt.setOnClickListener {
callApi()
}
}
private fun callApi() {
val params = HashMap<String?, Any?>()
params["name"] = "Ranjith"
params["mobile"] = 99*******
params["emailID"] = "var***#gmail.com"
params["password"] = "Ram#123"
params["countryCode"] = 91
RetrofitClient.instance.registerUser(params)
.enqueue(object : Callback<DefaultResponse>{
override fun onResponse(call: Call<DefaultResponse>, response: Response<DefaultResponse>) {
print(response)
if(response.isSuccessful)
{
Toast.makeText(applicationContext, response.body()?.msg, Toast.LENGTH_SHORT).show()
}else
{
var jsonObject: JSONObject? = null
try {
jsonObject = JSONObject(response.errorBody()!!.string())
val code = jsonObject.getString("code")
val error = jsonObject.getString("error")
val message = jsonObject.getString("msg")
Toast.makeText(applicationContext, message+"\n"+code+"\n"+error, Toast.LENGTH_LONG).show()
} catch (e: JSONException) {
Toast.makeText(applicationContext, e.toString(), Toast.LENGTH_LONG).show()
e.printStackTrace()
}
}
}
override fun onFailure(call: Call<DefaultResponse>, t: Throwable) {
Toast.makeText(applicationContext, t.toString(), Toast.LENGTH_SHORT).show()
}
})
}
}
Interface Api
interface Api {
#FormUrlEncoded
#POST("/api/v1/******/****/register")
fun registerUser(
#FieldMap params: HashMap<String?, Any?>
): Call<DefaultResponse>
}
RetrofitClient.kt object class
object RetrofitClient {
private const val BASE_URL = "http://3.1**.**5.1*1:****"
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
.method(original.method(), original.body())
val request = requestBuilder.build()
chain.proceed(request)
}.build()
val instance: Api by lazy{
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
retrofit.create(Api::class.java)
}
}
DefaultResponse.kt model data class
data class DefaultResponse(
#SerializedName("code")
val code: Int,
#SerializedName("err")
val error: Boolean,
#SerializedName("msg")
val msg: String
)
Through Postman

How to set baseUrl in Retrofit?

I want to set the BaseUrl in Retrofit to change dynamically between stage and live because i have an app that has stage and live version. So i made a spinner and the user can select either he wants. But the problem is that after the user select the flavor he wants and then wants to change again it doens't work because the baseUrl is not changing like it should be.
I have this class where is defined the API_URL but it's not working :
#Singleton
class SingleUrlApi {
companion object{
public var API_URL_STAGE = BuildConfig.STAGE
}
}
and then i have another function that uses this API_URL_STAGE
override fun getUrl(shopUrl: ShopUrl, vararg args: String): String {
return when (shopUrl) {
ShopUrl.API_BASE -> if (SingleUrlApi.API_URL_STAGE) {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_stage)
} else {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_live)
}
ShopUrl.WEB_BASE -> if (SingleUrlApi.API_URL_STAGE) {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_stage)
} else {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_live)
}
You can use OkHttp along with Retrofit.
Then, you can use an OkHttpInterceptor to change the URL of the request
public final class HostSelectionInterceptor implements Interceptor {
#Override public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String host = //logic to fetch the new URL
if (host != null) {
HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();
request = request.newBuilder()
.url(newUrl)
.build();
}
return chain.proceed(request);
}
}
An easy and effective way is to use this library: RetrofitUrlManager

OkHttp EventListener : byteCount value is always zero in responseBodyEnd callback

I am using EventListener callback for some analysis in my app but I am facing an issue where I am not getting the correct value byteCount in responseBodyEnd callback. It is always 0.
I am attaching the code below.
val client = OkHttpClient.Builder()
.eventListenerFactory(HttpEventListenerFactory.FACTORY)
.build()
val request = Request.Builder()
.url("http://jsonplaceholder.typicode.com/comments?postId=1")
.build()
with(client) {
newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d("OkHttp##", "Request failed")
}
override fun onResponse(call: Call, response: Response) {
handleResponse(response.body())
response.close()
Log.d("OkHttp##", "Response received")
}
})
}
MyEventListenerImpl.kt
public class HttpEventListenerFactory extends EventListener {
public static final Factory FACTORY = new Factory() {
final AtomicLong nextCallId = new AtomicLong(1L);
#Override
public EventListener create(Call call) {
long callId = nextCallId.getAndIncrement();
Log.d("OkHttp##", "next call id : " + nextCallId);
String message = String.format(Locale.US, "%04d %s%n", callId, call.request().url());
Log.d("OkHttp##", message);
return new HttpEventListenerFactory(callId, System.nanoTime());
}
};
#Override
public void responseBodyEnd(Call call, long byteCount) {
// this method never gets called
// byteCount here is always 0
printEvent("Response body end", callId);
}

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);

I get data using retrofit with post request give message Internal server error

I am using retrofit library with post request, but i did not found data. Give "Internal server error" message.
API_1 : http://www.fabgrad.com/dummy_api_1/
type : POST
data : { us_id:23 }
interface -
public interface FirstApi {
public static String URl = "http://www.fabgrad.com/";
#FormUrlEncoded
#POST("dummy_api_1")
Call<Titles> getData(#Field("us_id") String id);
}
Using retrofi in main activity -
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(FirstApi.URl)
.addConverterFactory(GsonConverterFactory.create())
.build();
FirstApi categoryMenuApi = retrofit.create(FirstApi.class);
String s="23";
Call<Titles> categoryMenuCall = categoryMenuApi.getData(s);
categoryMenuCall.enqueue(new Callback<Titles>() {
#Override
public void onResponse(Call<Titles> call, Response<Titles> response) {
Titles list = response.body();
}
#Override
public void onFailure(Call<Titles> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I am new in retrofit So please help
You only have to add / at the end of your endpoint #POST("dummy_api_1")
Just like:
#POST("dummy_api_1/")

Categories

Resources