internal server error in android with django server - android

my python code in django is:
#csrf_exempt
def login(request):
data = {'a': '1'}
if request.method == 'POST':
form=login_form(request.POST)
if form.is_valid():
f = form.cleaned_data
if sign_in.objects.filter(username=f['user'], password=hashlib.md5(f['pas'].encode()).hexdigest()):
return JsonResponse(data)
and in android:
ApiInterface apiInterface = ApiClinet.GetClinet().create(ApiInterface.class);
Call<String> call = apiInterface.GetHome_call("x","y");
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
this code work in postman and recive:
{
"a": "1"
}
but when run in android. recive internal sever error!
and I work on localhost.

The Error must either be in your ApiClient Code or else check your #POST("") correctly , you need to put forward slash at it's end like this: #POST("login/").
Hope this helps,If not please update your question with the Client Code .

Related

Instagram api - Retrofit2 - unable to do POST request

I am new to retrofit and I am trying to send a comment to a specific media using retrofit and the Instagram API.
The Instagram API tells me that my request must be:
curl -F 'access_token=ACCESS-TOKEN'
-F 'text=This+is+my+comment'
https://api.instagram.com/v1/media/{media-id}/comments
and the JSON response is :
{
"meta":
{
"code": 200
},
"data": null
}
So I made this retrofit grammar:
#FormUrlEncoded
#POST("v1/media/{media_id}/comments")
Call<Object> postComment(
#Path("media_id") String mediaId,
#Field("access_token") String accessToken,
#Field("text") String text);
My Retrofit Service:
public class RestClient
{
public static RetrofitInstagram getRetrofitService()
{
return new Retrofit.Builder()
.baseUrl(Constants.AUTH_URL)
.addConverterFactory(GsonConverterFactory.create())
.build().create(RetrofitInstagram.class);
}
}
My call (inside an AlertDialog get the text from an EditText) is :
Call<Object> call = RestClient.getRetrofitService().postComment(data.get(idx).getId(), access_token, titleEditText.getText().toString());
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Call<Object> call, Response<Object> response)
{
Log.d("response comment", ""+response.raw());
Toast.makeText(activity_instagram_feed_search.this, "Comments sent", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Object> call, Throwable t)
{
Toast.makeText(activity_instagram_feed_search.this, "error", Toast.LENGTH_SHORT).show();
}
});
My problem here is that I am receiving a code 400 error (Missing client_id or access_token URL parameter.).
It's like the api think I am doing a GET request.
I am really confuse, I would appreciate some wisdom :).
I managed to find the solution to my question.
So Ben P was wrong and the Curl -F is x-www-form-urlencoded.
I am in sandbox account mode and forgot to add comments scope to my loggin
WebView request.
So my WebView url is now:
private final String url = Constants.AUTH_URL
+ "oauth/authorize/?client_id="
+ Constants.CLIENT_ID
+ "&redirect_uri="
+ Constants.REDIRECT_URI
+ "&response_type=token"
+ "&display=touch&scope=public_content+comments";

Trouble get special character in retrofit 2 and gson

I'm trying to get a json list from a web service.
This is the json string return by server :
[{"categoryName":"Política"},{"categoryName":"Economía"},{"categoryName":"Cultura"},{"categoryName":"Deportes"}
The problem is converting in to the POJO. The special characters (í) it's appear like "Pol�tica".
This is the retrofit call function :
#GET("categories")
public Call<List<CategoryPojo>> getCategorias(#Query("sitename") String site)
this is the callback function:
Call<List<CategoryPojo>> call = restservice.getApiService().getCategorias(medio);
try {
call.enqueue(new Callback<List<CategoryPojo>>() {
#Override
public void onResponse(Call<List<CategoryPojo>> call, Response<List<CategoryPojo>> response) {
List<CategoryPojo> categories = response.body();
if (listener != null)
listener.onDataLoaded(categories);
}
#Override
public void onFailure(Call<List<CategoryPojo>> call, Throwable throwable) {
Log.e("Retrofit Error", throwable.getMessage());
}
});
this is the POJO:
public class CategoryPojo implements Serializable{
public CategoryPojo() { }
#SerializedName("categoryName")
private String name;
public String getName()
{
return this.name;
}
}
The result of the request to the Web services, (output in browser) is :
[{"categoryName":"Política"},{"categoryName":"Economía"},{"categoryName":"Cultura"},{"categoryName":"Deportes"},{"categoryName":"Salud"},{"categoryName":"Ciencia y Tecnología"},{"categoryName":"Medio Ambiente"},{"categoryName":"Medios"},{"categoryName":"Militar e Inteligencia"},{"categoryName":"Sociedad"}]
So, the return json has a good encoding...i think that maybe is about the way retrofit read the response.
I'm using retrofit-2.0.2, gson-2.6.1, converter-gson-2.0.2, okhttp-3.2.0.
Any help? please
You should check Content-type in the response headers. Look for the charset value and try to change that on the backend side to application/josn;charset=UTF-8. That worked for me.

How to handle null param values in Retrofit

We're moving from Apache's http client to Retrofit and we've found some edge cases where param values can be null.
Apache used to intercept these and turn them into empty strings, but Retrofit throws an IllegalArgumentException.
We want to replicate the old behavior so that it doesn't cause any unexpected issues out in production. Is there a way for me to swap these null values with empty strings before ParameterHandler throws an exception?
You can try the following:
My web service (Asp.Net WebAPI):
[Route("api/values/getoptional")]
public IHttpActionResult GetOptional(string id = null)
{
var response = new
{
Code = 200,
Message = id != null ? id : "Response Message"
};
return Ok(response);
}
Android client:
public interface WebAPIService {
...
#GET("/api/values/getoptional")
Call<JsonObject> getOptional(#Query("id") String id);
}
MainActivity.java:
...
Call<JsonObject> jsonObjectCall1 = service.getOptional("240780"); // or service.getOptional(null);
jsonObjectCall1.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.i(LOG_TAG, response.body().toString());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
Logcat output:
If using service.getOptional(null);
04-15 13:56:56.173 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"Response Message"}
If using service.getOptional("240780");
04-15 13:57:56.378 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"240780"}

Retrofit 2.0, request GET to a .json file as endpoint

Hello Im working in a test with Retrofit 2.0 and one of the test is making a resquest to a url that finish with .json:
Example: https://domain.com/contacts.json
baseURl: https://domain.com/
endPoint: /contacts.json
Which is a file, but I want to make a normal GET request and get the json inside directly
If you have control over your web server, you can customize it supports .json file as text/plain or application/json. Please see my following screenshot (I have done with IIS 7.5)
The following screenshot is a request using PostMan:
build.gradle file:
dependencies {
...
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
}
WebAPIService.java:
public interface WebAPIService {
#GET("/files/jsonsample.json")
Call<JsonObject> readJson();
}
MainAcitivty.java:
Retrofit retrofit1 = new Retrofit.Builder()
.baseUrl("http://...")
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIService service1 = retrofit1.create(WebAPIService.class);
Call<JsonObject> jsonCall = service1.readJson();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.i(LOG_TAG, response.body().toString());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Logcat:
04-15 15:31:31.943 5810-5810/com.example.asyncretrofit I/AsyncRetrofit: {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}
Hello I found a solution to get the file using your code and it really works now but I haven't touch the MIME on the web server, I think I didn't have added the Converter in the code I guess. Thank you.
WebAPIService.java:
public interface WebAPIService {
#GET("/contacts.json")
Call<JsonObject> getContacts();
}
MainAcitivty.java:
Retrofit retrofit1 = new Retrofit.Builder()
.baseUrl(BuildConfig.API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIService service1 = retrofit1.create(WebAPIService.class);
Call<List<Contact>> jsonCall = service1.getContacts();
jsonCall.enqueue(new Callback<List<Contact>() {
#Override
public void onResponse(Call<List<Contact>> call, Response<List<Contact>> response) {
Log.i(LOG_TAG, response.body().toString());
}
#Override
public void onFailure(Call<List<Contact>> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});

How to stream real time data using Retrofit

I want to observer changes from server in my android app.
So I'm using this interface for open stream with server.
public interface Service {
#GET("/n/{id}/streaming")
void streamThreads(#Path("name_space_id") String Id, #QueryMap Map<String, String> options,#Query("exclude_types") String type, Callback<Object> callback);
}
and this is my method where I can get response in my activity
server.streamThreads(accountInfo.getId(), map, "thread", new Callback<Object>() {
#Override
public void success(Object o, Response response) {
String json = (String) o;
Log.i(TAG,json);
}
#Override
public void failure(RetrofitError error) {
Response r = error.getResponse();
if (r != null)
Log.e(TAG, "error: " + r.getReason());
}
});
So I tested method in web browser and life stream works.
But response comes in my mobile app every 30 minutes. I'm using one activity and call method onCreate().
Thanks
Retrofit provides an #Streaming annotation.
The unread byteStream can then be obtained from the raw OkHttp ResponseBody.

Categories

Resources