I am working in an android application that has to send user email through post method. The api endpoint is at https://api-iddog.idwall.co/ when i already run some tests and was able to GET values from here. Im using Loopj Library.
However, i've been tasked with using this endpoint:
https://api-iddog.idwall.co/signup
The documentation guide shows that i need to construct the POST method using the following parameters:
using Content-Type: application/json header
and the post URL should be something like:
Api Post Doc
With all that in mind, i got the create a method called attempPost(). On this method im creating the AsyncHttpRequest object, RequestParams object and storing the valid e-mail typed by the user.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonEmail = new JSONObject();
try {
jsonEmail.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Dog", " " + jsonEmail.toString());
params.put("-d", jsonEmail);
client.addHeader("Content-Type", "application/json");
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
}
});
}
This method is called in a OnclickListener, and the log is returning a message called BadRequest and Status Code 400. I already tried to apply some code examples from Loopj doc but i didnt work. Can someone give me an insight in what i am doing wrong ? From what i can gather the success response should be a String(Token) and i need this token to complete the project.
EDIT.
I worked a little more through documentation and other examples here on Stack and i found this: POSTing JSON/XML using android-async-http (loopj)
In the accepted answer there is an example on how to post JSON.
Then i made a few changes in my attempPost method.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", "your#email.com");
} catch (JSONException e) {
e.printStackTrace();
}
client.post(getApplicationContext(), url, jsonParams, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}
But Android Studio is telling me to convert jsonParams into a entity. In the example i got from stack its uses the following code to achieve that:
StringEntity entity = new StringEntity(jsonParams.toString());
However my android studio gets an horror that says:
Unhandled exception : java.io.UnsupportedEncodingException,
Until this moment i could not figure a way to solve this.
I managed to make it work, the API its now returning a proper response and status code 200. I converted the JsonObject into a ByteArrayEntity since the StringEntity was not an option.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
ByteArrayEntity be = new ByteArrayEntity(jsonParams.toString().getBytes());
//TODO create a class to handle JSON post, getmethods and parse token value
client.post(getApplicationContext(), API_URL, be, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("Dog", "onSucess " + response.toString());
Log.d("Dog", "status code " + String.valueOf(statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("Dog", "" + errorResponse.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}
Related
I am not familiar with JSON so if I am using wrong terms, sorry for that.
So I have this URL:
final String PRICE_TRY_URL = "https://api.coindesk.com/v1/bpi/currentprice/try.json";
And it returns something like this:
Formatted JSON Data
{
"time":{ },
"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi":{
"USD":{
"code":"USD",
"rate":"6,911.7500",
"description":"United States Dollar",
"rate_float":6911.75
},
"TRY":{
"code":"TRY",
"rate":"35,738.0058",
"description":"Turkish Lira",
"rate_float":35738.0058
}
}
}
All I want to do is reach TRY's rate.
I get that data with the code below.
public void doNetworking(){
AsyncHttpClient client=new AsyncHttpClient();
client.get(PRICE_TRY_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("BitcoinTracker","Succes in doNetworking");
// byte[] responseBody can be parsed to a json object.
parseJson(responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("BitcoinTracker", "Fail " + error.toString());
}
}
);
And here is my method :
public void parseJson(byte[] responseBody){
try {
JSONObject bitcoinJson =new JSONObject(new String(responseBody));
String currency= bitcoinJson.getString("bpi");
Log.d("bitcoinmanager",currency);
} catch (JSONException e) {
Log.d("BitcoinPrice","BitcoinPriceManager onSucces converting json from byte[] failed.");
e.printStackTrace();
}
}
As you can see above I use this statement :
String currency= bitcoinJson.getString("bpi");
And with this statement, I can't reach my destination point which is TRY's rate. How can I navigate in JSON formatted text?
NOTE: I add the getting JSON data part to make sure that my question is clear, hope it is not too much.
If you're using Android, no need to use anything external:
JSONObject bitcoinJson = new JSONObject(responseBody);
JSONObject bpi = bitcoinJson.getJSONObject("bpi");
JSONObject tr = bpi.getJSONObject("TRY");
String rate = tr.getString("rate");
Original answer using the org.json.simple library, before question was tagged as Android:
JSONObject bitcoinJson = (JSONObject)new JSONParser().parse(new String(responseBody));
JSONObject bpi = (JSONObject)bitcoinJson.get("bpi");
JSONObject tr = (JSONObject)bpi.get("TRY");
String rate = (String)tr.get("rate");
Note that instead of constructing a string to pass to the JSONParser, it's a bit more efficient just to give it access to the Reader directly.
You can use this code with Gson library:
client.get(PRICE_TRY_URL, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
// called when response HTTP status is "200 OK"
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(responseBodyString);
JsonObject bpi = jsonObject.get("bpi").getAsJsonObject();
JsonObject tryObject = bpi.get("TRY").getAsJsonObject();
String rate = tryObject.get("rate").getAsString();
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
}
);
There are examples here https://github.com/codepath/android_guides/wiki/Using-Android-Async-Http-Client
My put method is working fine, but just changing the put request to Delete then its not working,, I tried even by sending its header. but still not working. I even tried Json object to set the parameter. Thanks in advance.
StringRequest stringRequest = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("blalala", response);
String qtyReserved1 = response.toString();
Toast.makeText(mContext, "ok" + qtyReserved1, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "not ok" + username + Integer.toString(inventoryId), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("screen_name", username);
params.put("inventory_id", Integer.toString(inventoryId));
params.put("pending", "true");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MySingleton.mySingletonInstance(mContext.getApplicationContext()).addToRequestque(stringRequest);
Volley library don't send body when you using DELETE method. You can try other library. I am providing you an example by using loopj library
Add dependency in your gradle
compile 'com.loopj.android:android-async-http:1.4.9'
Request your web Api
RequestParams requestParams = new RequestParams();
requestParams.put("screen_name", "mariyam.shimaanath");
requestParams.put("inventory_id", 19);
requestParams.put("pending", true);
String url="192.168.4.31/api/canteen/cart";
new AsyncHttpClient().delete(url, requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String rs = new String(responseBody);
// do whatever you want
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
After lots of research, thank God I'm managed to solve the problem,, Not exactly solved the problem had in Delete request in Volley. But, I had to changed the method i need to request from server side. I changed the request to post method, I know it might not be good practice and solution, but now i managed to delete from sever. thats what i need.
I have successfully installed the loopj async http client and I am having this issue whilst executing this code:
protected void PostData(Integer Question_ID,Integer ResponseChosen_ID) throws IOException {
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params1 = new RequestParams();
params1.add("Question_ID",Question_ID.toString());
client.post("http://10.0.2.2:443/SwlLogin.php", params1, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.print(params1);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
Error:
Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.
Is this because of the UI thread but the whole point of using this client is that it can bypass the UI thread exception and execute a http request?
There is no logcat.
Any advice on how to resolve this would be much appreciated.
You can call the PostData() with the following workaround
new Handler(Looper.getMainLooper()).post(new Runnable(
{
#Override
public void run()
{
postData();
}
})) ;
It is exactly a UI thread issue.
I used loopJ AsyncHttpClient for several projects, Can I know the whole code/class that you are implementing the loopJ?
You should implement you client like this if you are expecting String from your php
client.post("http://10.0.2.2:443/SwlLogin.php", params1, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("RESPONSE", responseString);
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Log.d("RESPONSE", responseString);
}
});
php code :
ob_start();
error_reporting(0);
var_dump($_REQUEST);
var_dump(headers_list());
i spend a lot of time to search how resolve my problem but stil unsuccessful, so i hop some one could help me.
I make my app with android studio:
i finish my page with login and httm request (100% working to conect and creat new account) and now i trying to make Get request to my server and get username rerver turn my array of bytes that i try to cast on string and in obtain just null "".
there is my code:
mainActivity.java
Button b = (Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("email", "test3#t.com");
// Handle request
client.get("https://......../user/get/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
System.out.println("response ----" + response);
String res = new String(response); //convetion Byte[] to String that i use
Context context = getApplicationContext();
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
System.out.println("res ----" + res);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
System.out.println("errorResponse -----"+errorResponse);
String res = new String(errorResponse);
Context context = getApplicationContext();
// Toast.makeText(context, res, ast.LENGTH_SHORT).show();
System.out.println("ERROR--" + res);
}
});
}});
Server side it's look like this :
views.py
def get_users(req):
"""
Use url :
https://...../user/get/
With arguments :
?email=EMAIL
"""
email = req.GET.get('email')
if email is not None:
exists = User.objects.filter(email=email)
if len(exists) == 0:
return HttpResponse("Error invalid email !")
else:
res = "%s:%s" %(exists[0].username, exists[0].points)
return HttpResponse(exists[0].username)
else:
return HttpResponse("Missing information !")
And that what i obtain on Android Monitor:
I/System.out: response------[B#4136b800
I/System.out: res --------
ass you can see after covertion i have just NULL .
Can Someone help me plz
Can you anyone help me giving good example on how to use retrofit for posting large data from my local DB to mysql server.
Currently I am using async-http API and strangely there is always memory error coming up. I am looking for better API that wont give memory error while uploading huge text of data.
This is my setup:
List<TextDetails> unTextList = dbvalue.getTextData();
for (TextDetails td : unTextList)
{
String textID = td.getSerialNumber();
String textSMS = td.getText();
String textAddress = td.getFulladdress();
String textDate = td.getFulldate();
String textException = td.getExceptiontext();
textDetailsBackUpDataOnline(textID , textSMS, textAddress, textDate, textException);
}
private void textDetailsBackUpDataOnline(final String textID ,
String textSMS, String textAddress, String textDate, String textException)
{
final String uploadWebsite = url_backup_text_details;
RequestParams requestParams = new RequestParams();
requestParams.put("textSMS", textSMS);
requestParams.put("textAddress", textAddress);
requestParams.put("textDate", textDate);
requestParams.put("textException", textException);
Text_HttpClient.post(uploadWebsite, requestParams, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
{
Log.e("textID", "= how many times");
}
#Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] errorResponse, Throwable e)
{
e.printStackTrace(System.out);
}
});
}
Text_HttpClient class has the following:
public class Text_HttpClient
{
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
{
client.get(url, params, responseHandler);
}
public static void post(String url, RequestParams requestParams, AsyncHttpResponseHandler responseHandler)
{
client.post(url, requestParams, responseHandler);
}
}
1) Write service interface:
public interface ArticleGetListService {
#FormUrlEncoded // Request will have "application/x-www-form-urlencoded" MIME type
#POST("/api/Article/ArticleGetList")
public void getArticleList(#Field("LanguageCode") String languageCode,
#Field("CategoryId") String categoryId,
#Field("Token") String token,
Callback<ArticleViewPojo> response); //POJO: The json retrieved from the server is added to this class.
}
Here my Rest service requires 3 Parameters, change it as your need.
2) Write POJO for converting JSON returned from Rest Api into java class object so you can use data.
Just copy your JSON into this site, choose JSON source type, annotation as Gson. It will generate POJO for your JSON automatically.
3)On your Main Activity
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(baseUrl)
.build();
ArticleGetListService articleGetListService = restAdapter.create(ArticleGetListService.class);
Callback<ArticleViewPojo> callback = new Callback<ArticleViewPojo>() {
#Override
public void success(ArticleViewPojo model, Response response) {
//use model which is data returned to you
}
#Override
public void failure(RetrofitError error) {
//handle error
}
};
//START REST CALL
articleGetListService.getArticleList(languageCode, categoryId, token, callback);
//above parameters are those written in service interface at 1
//Whole Url is baseUrl+ArticleGetListService in above example