I'm an experienced developer with android and currently i am developing android application that has Django as its server side on heroku cloud.
I'm pretty new to django and django rest framework so i dont really get how to use it except for the guide on their website.
What i was trying to do recently was using Volley/AsyncHttpClient/Apache Http to contact with my django server.
With each of these libraries i got Http 500 error on django in his console output.
What i tried to do on each of them is adding data to the body or parameters.
On Volley - i overrided the getParams and added them to hash
on AsyncHttpClient - i made RequestParams
on HttpClient(apache) - i used a list of NameValuePair and added them as entity of UrlEncodedForm to the http post request.
i also tried on volley and asynchttpclient to add data to the body of the request and it didn't worked also.
I even thought of changing my server side because of all the trouble Django is causing me , so please if anyone have the answer please give it :)
This is my Server Side(Django):
class User(APIView):
queryset = AppUser.objects.all()
def get(self,request,format=None):
users = AppUser.objects.all()
serialized_users = UserSerializer(users, many=True)
return HttpResponse(serialized_users.data)
def post(self,request):
user_serializer = UserSerializer(data=request.DATA)
if user_serializer.is_valid():
user_serializer.save()
return HttpResponse(status.HTTP_201_CREATED)
return HttpResponse(status=status.HTTP_406_NOT_ACCEPTABLE)
**There's no point to show the urls/models/serializer because it all works on the google chrome with the GET method.
Android(apache http client):
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
paramsList.add(new BasicNameValuePair("user",userJson));
post.setEntity(new UrlEncodedFormEntity(paramsList));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
}
Android (AsyncHttpClient):
try {
RequestParams params = new RequestParams();
params.put("user",userJson);
mClient.post(msg.getText().toString(),params,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 201) Toast.makeText(MainActivity.this,"Success" , Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
} catch (Exception e) {
}
I'm really clueless what to do next because i think i covered all my options contacting my server...
Thanks
If I am not wrong, the message in console just says Http 500 Server error without the cause right?
To debug it more, add following to your settings(base.py)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'ERROR',
'class': 'logging.StreamHandler',
'stream': sys.stderr
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
'propogate': True,
'level': 'ERROR',
}
}
}
This few lines in your settings will print the cause of 500 error in the console, you might get clue to what you are doing wrong.
Related
I am trying to get make a post request in Android using AsyncHttpClient using this code:
JSONObject jsonParams=new JSONObject();
try {
jsonParams.put("email", email);
}
catch (Exception e){
}
try {
StringEntity entity = new StringEntity(jsonParams.toString());
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(),URL,entity, "application/json", new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {}
});
I am trying to access this data sent in the post request in my Python server. However, whenever I do request.json in my Python server, I get 'None' as response.
I also tried request.get_json(force=True) but getting 404 error code.
I dont really know if the data is being sent by the client APP or I am making a mistake while trying to retrieve it at the server side. Please help me with this issue.
String content = new String(responseBody);
Log.e("SUCCESS_RESP",""+content);
Hello guys I'm new to restful service.
My friend created REST backend with Spring.
When I post this URL --> http://smartcar.tobaconsulting.com:9999/api/v1/login with postman or angularjs http.post, it's fine.
You guys can check it out in postman by including this body
{ "username":"alvin", "password":"alvin" }
and set content type to JSON (application/json).
But when I code to Android, why it's not working and return 500 error code.
My friend said that I'm not including header. I'm using loopj http library http://loopj.com/. Here is my android code
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://smartcar.tobaconsulting.com:9999/api/v1/login", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
});
Please help me guys. I trying to solve this problem for hours and haven't find any clue.
Thanks
i checked your URL no error in server response
Access-Control-Allow-Credentials →true
Access-Control-Allow-Methods →GET, POST, PUT, DELETE
Access-Control-Allow-Origin →chrome-extension://mkhojklkhkdaghjjfdnphfphiaiohkef
Access-Control-Expose-Headers →X-AUTH-TOKEN
Content-Length →0
Date →Thu, 07 Apr 2016 08:35:26 GMT
Server →Apache-Coyote/1.1
X-AUTH-TOKEN
→eyJ1c2VybmFtZSI6ImFsdmluIiwiZW1haWwiOiJhbHZpbkBhbHZpbi5jb20iLCJleHBpcmVzIjoxNDYwODgyMTI2MDc4LCJvd25lcmlkIjo2LCJteVJvbGVzIjpbIlVTRVIiLCJBRE1JTiJdfQ==.M9/71trIPbnXxCh7avSWBK42UDXUxWYXZrNOlHhO7iQ=
I would personally suggest using Volley lib for android, there is some useful method inside volley and google strongly recommended that
Transmitting Network Data Using Volley
I am using StringEntity with AndroidAsyncHttp but it is deprecated. Is there another way to get this to work while sending my json string in the way I am to my web service?
public void getPropertyImagesAsync(final String[] params) {
JsonStructure jsonStructure = new JsonStructure();
jsonStructure.methodName = "getPropertyWorkorders";
jsonStructure.serviceName = "mobileapi";
jsonStructure.parameters = params;
String jsonString = new Gson().toJson(jsonStructure);
StringEntity entity = null;
try {
entity = new StringEntity(jsonString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(visnetawrap, BASE_URL + "/amf/gateway/?contentType=application/json", entity, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
AppUtils.outputJsonString(s);
}
#Override
public void onSuccess(int i, Header[] headers, String s) {
AppUtils.outputJsonString(s);
}
});
}
Keep an eye on the situation, but you can probably get away with continuing to use StringEntity for now.
StringEntity is actually part of Apache HTTP, not android-async-http. Google deprecated the entire Apache HTTP API in SDK 22, and removed it from the stub library in SDK 23 (M preview). It reportedly still runs on M devices, but you can't compile it.
Unfortunately, android-async-http was designed around Apache HTTP. Worse, it exposes its use of that API, so it can't be changed without causing breakage. The developers have announced plans to ensure continued support, possibly by introducing a dependency on the standalone Apache HTTP.
I recommend you to use a library for your network operations. You can use Retrofit. It's a powerful library and easy to use.
http://square.github.io/retrofit/
I am doing a REST client in Android to consume a webService hosted in Amazon EC2.
When a acess the URL in bowser, it's work fine. But when i tried to acess the webservice in the android app, i received a error 404.
URL urla = new URL(SERVICE_URL);
HttpGet method= new HttpGet(new URI(SERVICE_URL));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(SERVICE_URL));
HttpResponse response = client.execute(method);
int responseCode = response.getStatusLine().getStatusCode();
When I provide the rule "All" Access In the amazon EC2, it's work fine, but i believe it's not a better way.
All Rule:
*Ports: All
Protocol: All
Source: All*
Does anyone know a better way to access the REST webservice hosted in the EC2 with a client android?
Try using AsyncHttpClient library instead thats simple and easy. Here is a sample code
AsyncHttpClient client;
client.get("http://ec2-xx-xxx-xx-xx.compute-1.amazonaws.com:8080/MyService1/jaxrs/helloworld",
new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
#Override
public void onSuccess(String response) {
try {
// JSON Object
tv1.setText(response);
} catch (Exception e) {
tv1.setText(e.getMessage());
}
}
});
Simple give the public DNS of your instance with port of server, then path to the function call of your service.
This is how I did it.
I'm trying to implement simple Androd client with RestLet for my thesis.Evrything works well over HTTP but I have to get it to work over HTTPS with self-signed certificate and this is were I have problems.
I was unable to find any helpful articles or anything similar about how to implement this on Android with RestLet. I know how to do this with code from Android Developers but I need to do this with Restlet classes.
I managed to implement some code which will execute GET method ( though very slow, it takes about 20-30 seconds to get data from server) but i have problems with PUT method.
I used the following code to implement HTTPS client
private static ClientResource makeInstance(String url, Context con) {
Reference reference = new Reference(url);
Log.d("URL", url);
String keyStoreFileAbsolutePath = PreferenceManager
.getDefaultSharedPreferences(con).getString(
Constants.PREF_KEY_KEYSTORE_FILE_PATH, "");
System.setProperty("javax.net.ssl.trustStore",keyStoreFileAbsolutePath);
System.setProperty("javax.net.ssl.trustStorePassword", "ks090278d");
System.setProperty("ssl.TrustManagerFactory.algorithm",
javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm());
org.restlet.Context context = new org.restlet.Context();
context.getAttributes().put("hostnameVerifier", new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
ClientResource resource = new ClientResource(context, reference);
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients()
.add(new HttpClientHelper(null));
resource.release();
return resource;
}
and I'm using it like this
ClientResource request = new ClientResource(url);
request.setRetryAttempts(0);
Series<Header> responseHeaders = (Series<Header>) request.getResponse()
.getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
responseHeaders = new Series(Header.class);
request.getRequestAttributes().put("org.restlet.http.headers",
responseHeaders);
}
responseHeaders.add(new Header("Accept", "application/json;"));
responseHeaders.add(new Header("Content-Type", "application/json;"));
responseHeaders.add(new Header("Authorization",
"Basic ZXN0dWRlbnQ6YW5kcm9pZA==;"));
try {
request.put(new JsonRepresentation(jsonString));
Response response = request.getResponse();
if (response != null) {
Log.d("Response", "HTTP Response: " + response.toString());
ResponseHandler
.handleResponse(response);
}
} catch (Exception e) {
}
When I execute this request I'm getting "Internal server error - 500". I'm using basically the same code for GET method only insted of
request.put(new JsonRepresentation(jsonString));
I'm doing
request.get();
and it works (though very slow as I mentioned above).
I checked if this is due to some error with the server but I think is not because I managed to get appropriate response when I'm using code similar to the code from Android Developers and also when I'm trying to execute PUT to the same URL from RestClient in Chrome.
Can anyone give me any suggestions how to get this to work? I'm not sure if my aproach is good to begin with, may be that I'm gooing in the wrong direction from the start.
Thnaks in advance.