I want to get the session id from the login panel and I am using Retrofit to make the request.
But when looking for the headers in the response I did't find any cookie set
And here is the request code:
Retrofit retrofit = new Retrofit.Builder().baseUrl(getResources().getString(R.string.baseurl)).addConverterFactory(GsonConverterFactory.create(gson)).build();
API api = retrofit.create(API.class);
Call<ResponseBody> call = api.loginhtml(et_user.getText().toString(), et_pass.getText().toString());
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String head = String.valueOf(response.headers());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
by using this code you can have the session
response.headers().get("Set-Cookie")
Related
public void makeGetRequest() {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success" , " " + response.body().bytes().length);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
I have this code and it makes a get request to my server with the async method. What I want is to make the same request multiple times. For example, I want to make get request 100 times. I don't want to use observables or other external libraries if possible. Is there anyone who can help me with that?
You can make call multiple times just see the below code where I have used methods for this purpose. In onResponse method after performing operation on data you get from server you can make another call to the same API by using a variable sizeOfCall and decrementing it untill it equals to zero. Below is the full code for it.
public class RequestActivity extends AppCompatActivity {
int sizeOfCall = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
callAPI();
}
private void callAPI(){
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
// Call API
makeGetRequest(call);
}
private void makeGetRequest(Call<ResponseBody> call) {
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success", " " + response.body().bytes().length);
// Perform your operations here and call API againg after that
sizeOfCall--;
if (sizeOfCall > 0) {
callAPI();
} else {
// No more calls needed
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
}
}
Create a broadcast reciever and put your retrofit request in that. Now call it using alarm manager.
public class YourBroadCastReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
yourRetrofitCode();
}
private void yourRetrofitCode(){
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success" , " " + response.body().bytes().length);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
}
}
now call using this code :
Intent sendDeviceInfoIntent = new Intent(this, YourBroadCastReciever.class);
PendingIntent yourintent= PendingIntent.getBroadcast(this, 0, sendDeviceInfoIntent, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+1000, 60000, yourintent);
so that every 5 min this will call your broadcast reciever and this will also works in background
I tried to post raw data to server using retrofit method, but I receive the failure response like resĀ fail: Response{protocol=http/1.1, code=500, message=Internal Server Error, url=http://192.168.1.9:8000/api/deviceinfo}
apiService = RetrofitSingleton.createService(ApiService.class);
spyApp = new SpyApp();
Call<ModelResponse> call = apiService.eventsUpdate(jsonObj);
call.enqueue(new Callback<ModelResponse>() {
#Override
public void onResponse(Call<ModelResponse> call, Response<ModelResponse> response) {
Log.e("response", new Gson().toJson(response.body())); //This shows null
if (response.isSuccessful()) {
String status = response.body().getData().getStatus();
} else {
Log.e("res fail", response.toString());
}
}
#Override
public void onFailure(Call<ModelResponse> call, Throwable t) {
Log.e("failure",t.getMessage());
}
});
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?
this is my interface:
public interface ApiService {
#GET("uploads/{file_name}")
Call<ServerResponse> downloadFile(#Path("file_name") String fileName);
}
and this is my downloading code :
private void downloadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
ApiService getResponse = ApiClient.getClient().create(ApiService.class);
Call<ServerResponse> call = getResponse.downloadFile(file.getName());
call.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
}
});
}
Probably, you are referring that the method "enqueue()" is called, but it's not the onResponse one.
Please wait some time (a minute is fine) and make sure that onResponse nor onFailure are called.
If you want more info, you can use the HTTP logging interceptor
#POST("uploads/{file_name}")
Observable<Document> getDocumentsList(#Path("file_name") String fileName);
and the code webservice call should be
Observable<Document> listObservable = mApiService.getDocumentsList(path);
subscribe(listObservable, new Consumer<Document>() {
#Override
public void accept(Document resourceDtos) throws Exception {
fillDocs(resourceDtos.getData());
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
fillDocs(throwable.getMessage());
}
});
I would like to handle my response from server , but I don't know how JSON (from server) its looks like. So I tried to display response as String , but I cant do it. Is it possible to display response as String? And then handle the response correctly. thanks
(Retrofit 1.9)
LoginService loginService = RetrofitClient.createService(LoginService.class);
loginService.searchOffer(getToken(), offerSearch, new Callback<String>() {
#Override
public void success(String offerSearchRequestResource, Response response) {
String responseFromSercer = response.getBody();
}
#Override
public void failure(RetrofitError error) {
}
});
change your response model to
JSONObject (from Gson)
then in your
public void success(...){response.body.toString();}
like this:
Call<JsonObject> call = YOUR_API_INTERFACE().YOUR_METHOD(YOUR_PARAMS);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, #NonNull Response<JsonObject> response) {
if(response.isSuccessful()) {
String responseFromSercer = response.body.toString();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
.....
}
});
If you are sure the request runs successfully and there is a response back...use
System.out.println(response.getBody());
i'd also suggest you add Logging Interceptors here so that you can get a detailed view of all your API calls
I need make POST request with parameters "guid=1" in Body. i use Retrofit2
I try :
#POST("/api/1/model")
Call<ApiModelJson> getPostClub(#Body User body);
User Class:
public class User {
#SerializedName("guid")
String guid;
public User(String guid ) {
this.guid = guid;
}
MailActivity:
User user =new User ("1");
Call<ApiModelJson> call = service.getPostClub(user);
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response) {
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
How make this request?
you have to call call.enqueue, providing an instance of Callback< ApiModelJson>, where you will get the response. enqueue executes your backend call asynchronously. You can read more about call.enqueue here
With code below, you can make the request synchronously:
ApiModelJson responseBody = call.execute();
If you want it to be asynchronous:
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
}
});