Getting Internal Server Error 500 in Retrofit - java

I know there are a lot of threads regarding this and i did go through them and also looked into the same Retrofit POST example,but i'm not sure what am i doing wrong in this,lemme know if any
#Multipart
#POST("api/customerdetail")
Call<Array> addUser(#Part("CustomerName") String CustomerName, #Part("CustomerId") String CustomerId, #Part("UserId") String UserId, #Part("VehicleCompanyName") String VehicleCompanyName, #Part("VehicleModelType")String VehicleModelType, #Part("VehicleNumber")String VehicleNumber, #Part("Location")String Location);
//METHOD USED TO CALL
private void simpleMethod() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://endpoint.net/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GetDataService service = retrofit.create(GetDataService.class);
Call<Array> arrayListCall = service.addUser("Peter Jenkins", UUID.randomUUID().toString(),"user2","AUDI","R3","BVZ-009","-55,-93.23"); arrayListCall.enqueue(new Callback<Array>() {
#Override
public void onResponse(Call<Array> call, Response<Array> response) {
Log.e("RESPONSE",response.toString());
}
#Override
public void onFailure(Call<Array> call, Throwable t) {
Log.e("ERROR",t.toString());
} }); }
Works like a Charm in Postman,and uploading an image is not necessary,atleast from the api end
Any inputs would be deeply appreciated

Related

Why isn't my post retrofit request working?

I have an app that should upload the following parameters
and here I have my code
#POST("task")
Call<ResponsetTask> API_Task(#Header("Authorization") String key, #Body RequestBody body);
[3
and
private void Analizar() {
File file=new File(path);
RequestBody requestBody =RequestBody.create(MediaType.parse("image/jpg"),file);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("message", Constantes.MESSAGE);
builder.addFormDataPart("filecomment", Constantes.FILECOMMENT);
builder.addFormDataPart("api_token", Constantes.api_token);
builder.addFormDataPart("user_id", Integer.toString(Constantes.id));
builder.addFormDataPart("image","image.jpg",requestBody);
MultipartBody body = builder.build();
Call<ResponsetTask>call=conexion2.API_Task(Constantes.AUTH,body);
call.enqueue(new Callback<ResponsetTask>() {
#Override
public void onResponse(Call<ResponsetTask> call, Response<ResponsetTask> response) {
if(response.isSuccessful()){
Constantes.api_task=response.body().getTaskId();
}
}
#Override
public void onFailure(Call<ResponsetTask> call, Throwable t) {
}
});
}
The problem is that the post does not work and does not tell me why I have a breakpoint in my code the BodyRequest is built but when it comes to the call it simply jumps to the end that is to say the onResponse () and the onFailure () skip the code seems work and the app does not hang or give Exception
I appreciate any help friends
This issue is that you are trying to pass data with multipart, Its an easy fix
Add this library
implementation "com.squareup.retrofit2:converter-scalars:$retrofit_version"
and this convertor factory
.addConverterFactory(ScalarsConverterFactory.create()) in your retrofit builder
.sample code is given below
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();

Retrofit POST Request with body parameters android

I need to execute post request with retrofit but i have a problem which i can't understand very well. Before trying with code i tested api call with Postman and request look like this:
Here is my android code:
public class API {
private static <T> T builder(Class<T> endpoint) {
return new Retrofit.Builder()
.baseUrl(Utils.API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(endpoint);
}
public static AllRequests request() {
return builder(AllRequests.class);
}
}
EDIT request:
#POST("api/android-feedback")
#Headers({"Content-Type: application/x-www-form-urlencoded", "Authorization: F##3FA##Rad!#%!2s"})
Call<String> sendFeedback(#Body FeedbackBody body);
FeedbackBody:
public class FeedbackBody{
private final String email;
private final String feedback;
public FeedbackBody(String email, String feedback){
this.email = email;
this.feedback = feedback;
}
}
And finally i construct the request and wait for response, the problem is that i receive message in onFail method
private void sendFeedbackRequest(){
API.request().sendFeedback(new FeedbackBody("testmeil#meil.com", "test feedback").enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
goToMainActivity();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
}
});
EDIT:
Still not working.. i think i figure it out where can be the problem, because server side wait for simple POST request without Json formatting, i think Retrofit use JSON formatting by default, and if i send POST request and format Body parameters with JSON the server will fail to parse my request, is there any chance to send simple POST request like at POSTMAN without formatting with JSON ?
Php api wait request to be send like this:
$_POST['feedback'] = 'blabla';
$_POST['email'] = 'blabla..';
and if he receive Json format request can't parse it and because of that i receive fail response.
First you need to create request( POJO Class)
public class FeedbackRequest {
public String email;
public String feedback;
}
when you call sendFeedbackRequest() pass the FeedbackRequest like below"
FeedbackRequest req = new FeedbackRequest();
req.email= "email";
req.feedback= "feedback"
sendFeedbackRequest(req)
after that your sendFeedbackRequest() should be like this
private void sendFeedbackRequest(FeedbackRequest request){
API.request().sendFeedback(request).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
goToMainActivity();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
}
});
And your retrofit request should be like this,
#FormUrlEncoded
#POST("api/android-feedback")
#Headers({"Content-Type: application/json", "Authorization: F31daaw313415"})
Call<String> sendFeedback(#Body FeedbackRequest request);
Now it should work. feel free to ask anything.
You are using a Gson converter factory. It might be easier to create a single object that represents your body, and use that instead of all individual parameters. That way, you should be able to simple follow along with the examples on the Retrofit website.enter link description here
There are also many site that let you generate your Plain Old Java Objects for you, like this one:
E.g. your Api call:
#POST("api/android-feedback")
Call<String> sendFeedback(#Body FeedbackBody feedback);
And your FeedbackBody class:
public class FeedbackBody{
private final String email;
private final String feedback;
public FeedbackBody(String email, String feedback){
this.email = email;
this.feedback = feedback;
}
}
Java:
#POST("/api/android-feedback")
Call<String> sendFeedback(#Body FeedbackBody feedback);
Kotlin:
#POST("/api/android-feedback")
fun sendFeedback(#Body feedback: FeedbackBody): Call<String>
Also, probably you forgot leading slash in the endpoint.
val formBody: RequestBody = FormBody.Builder()
.add("username", LoginRequest.username)
.add("password", LoginRequest.password)
.add("grant_type",LoginRequest.grant_type)
.add("client_id", LoginRequest.client_id)
.add("client_secret", LoginRequest.client_secret)
.add("cleartext", LoginRequest.cleartext)
.build()
#POST(EndPoints.GENERATE_TOKEN_URL)
#Headers("Content-Type: application/x-www-form-urlencoded")
suspend fun getLogin(
#Body formBody: RequestBody
): LoginResponse

How to convert cURL to retrofit correct form?

Sorry for my English. I want use this service. For determine the language of the text.
Request(Curl):
curl -X POST -d "outputMode=json" --data-urlencode text#ibm.txt -d "url=http://www.ibm.com/us-en/" "https://gateway-a.watsonplatform.net/calls/text/TextGetLanguage?apikey=%API_KEY%"
I use Retrofit for request.
public interface LanguageDetectionApi {
public static final String ROOT_URL = "https://gateway-a.watsonplatform.net/calls/";
#POST("/text/TextGetLanguage")
Call<List<PostModel>> getData(#Query("apikey") String apikey, #Query("text") String text);
}
Create retrofit object:
public class App extends Application {
private static LanguageDetectionApi _languageDetectionApi;
private Retrofit _retrofit;
#Override
public void onCreate() {
super.onCreate();
_retrofit = new Retrofit.Builder()
.baseUrl(_languageDetectionApi.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
_languageDetectionApi = _retrofit.create(LanguageDetectionApi.class);
}
public static LanguageDetectionApi getLanguageDetectionApi() {
return _languageDetectionApi;
}
}
And send request:
App app = new App();
app.onCreate();
app.getLanguageDetectionApi().getData("4978e60252ae102dfe1341146bb8cc3ec4bbbd78", textForRecognition).enqueue(new Callback<List<PostModel>>() {
#Override
public void onResponse(Call<List<PostModel>> call, Response<List<PostModel>> response) {
List<PostModel> posts = new ArrayList<>();
posts.addAll(response.body());
}
#Override
public void onFailure(Call<List<PostModel>> call, Throwable t) {
Toast.makeText(MainActivity.this, "An error occurred during networking", Toast.LENGTH_SHORT).show();
}
});
PostModel i generated in site http://www.jsonschema2pojo.org/.
Questions:
No response comes to me, although apikey are exactly valid.
How to specify in the interface parametr "outputMode=json"?
And I translated correctly cURL to LanguageDetectionApi?
It seems to me that the whole mistake in the class LanguageDetectionApi. Can you help deal with this? Thank you!
change url code like below:
public interface LanguageDetectionApi {
public static final String ROOT_URL = "https://gateway-a.watsonplatform.net";
#POST("/calls/text/TextGetLanguage")
Call<List<PostModel>> getData(#Query("apikey") String apikey, #Query("text") String text);
}
base url should be ony host name.

Consuming WS Rest with Retrofit2

I have a WS REST, that I need to consume by POST, which method "calculo" expects a XML as below in the key "xmlEntrada".
<xml>
<valor1/>
<valor2/>
<operacao/>
</xml>
I did the corresponding class to serialize, as expected by retrofit and SimpleXmlConverter
#Root(name="xml")
public class CalcRequest {
public CalcRequest(){
campo1 = campo2 = 0;
operacao = "";
}
#Element(name="valor1", required = false)
private float campo1;
#Element(name="valor2", required = false)
private float campo2;
#Element(name="operador", required = false)
private String operacao;
}
And I'm calling retrofit and all the stuff like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://server_name/wsRest/Project1.dll/")
.addConverterFactory(SimpleXmlConverterFactory.create())
.client(new OkHttpClient())
.build();
APIService API = retrofit.create(APIService.class);
Call<CalcResponse> call = API.EfetuaCalculo(calculo);
call.enqueue(new Callback<CalcResponse>() {
#Override
public void onResponse(Call<CalcResponse> call, Response<CalcResponse> response) {
AlertMessage(response.body().retorno());
}
#Override
public void onFailure(Call<CalcResponse> call, Throwable t) {
AlertMessage("Error. MSG: " + t.toString());
}
});
My method response serialization is fine, because I can read the error returned as XML, and it shows me that the request xml is arriving empty at the WS. I'm stucked on that by days, can anyone guess what's wrong?
Oh, here it's my APIService code:
public interface APIService {
#POST("calculo")
Call<CalcResponse> EfetuaCalculo(#Body CalcRequest xmlEntrada);
}

Make a GET and POST service call with Retrofit with the use of Protobuf (Protocol Buffer)

Can anyone please give me some example how we can use protobuf in retrofit - I tried but its failed with some error , let me give you a sample of my implementation on that.
I hope you guys will help me.
ApiInterface.java
public interface ApiInterface {
#GET
Call<CommonProto.Country> makeGetRequest(#Url String url);
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "**************************";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(Proto3ConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CommonProto.Country> call = apiService.makeGetRequest("Services/CountryServices/GetAllCountry");
call.enqueue(new Callback<CommonProto.Country>() {
#Override
public void onResponse(Call<CommonProto.Country> call, Response<CommonProto.Country> response) {
String bodyString = null;
try {
Log.e("RETROFIT ::::::: ", String.valueOf(response.body())+"TEST");
} catch (Exception e) {
Log.e("RETROFIT ERROR ::::::: ", e.getMessage()+"TEST");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<CommonProto.Country> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
}
);
when i run this way i got the error
java.lang.RuntimeException: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
my Proto.java file and also have Proto.proto file both are here in this link,
https://drive.google.com/folderview?id=0B4loQuzINvHCRUlNbk5LUXE1NXM&usp=sharing
Please let me know how to do this GET Req and also I was Struggling with POST Req.
you can create interface like this
public interface LoginInterface {
#FormUrlEncoded
#POST("url goes here")
Call<LoginResponseData> getUserLoginDeatail(#FieldMap Map<String, String> fields);
}
make an instance of retro file and call interface method something like this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("base url")
.build();
webApis = retrofit.create(WebApis.class);
Call<LoginResponseData> call = webApis.getCurrentRide(keyValue);
call.enqueue(new Callback<LoginResponseData>() {
#Override
public void onResponse(Call<LoginResponseData> call, Response<LoginResponseData> response) {
try {
} catch (Exception e) {
// customizedToast.showToast(context.getResources().getString(
// R.string.exception));
e.printStackTrace();
}
}
#Override
public void onFailure(Call<LoginResponseData> call, Throwable t) {
}
});
for protocol buffer you can find a reference here

Categories