I am trying to get response from my node.js server with MySQL database.
When I connect to server with my browser I get result like this:
[{"person_id":0,"age":18},{"person_id":1,"age":17},{"person_id":2,"age":30}]
What I want to do is to get the same result with my Android app after pressing the button.
I wanted to use LoopJ AndroidAsyncHttp:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
}
});
I know that I connected to server properly because I got log in server's console.
What is the easiest way to retrieve that data?
Create a model Person contain "person_id" and "age"
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000",new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String response = responseBody == null ? null : new String(
responseBody, getCharset());
Log.d("Response: ", response);
Gson gson = new Gson();
Person[] arr = gson.fromJson(response, Person[].class);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Related
I'm using android-async-http for rest request. When I doing post request then the response body is empty. When I use postman for the same request I received a response as JSONObject.
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(getResources().getString(R.string.api_user), getResources().getString(R.string.api_password));
String requestAddress = getResources().getString(R.string.api_base_address) + getResources().getString(R.string.api_event_address);
JSONObject params = new JSONObject();
params.put("name", mEditTextName.getText().toString());
params.put("place", mEditTextPlace.getText().toString());
params.put("dateAndTime", DateUtils.sdfWithFullTime.format(DateUtils.sdfWithTime.parse(mEditTextDate.getText().toString())));
Log.d(TAG, "onClick: " + params.toString());
StringEntity stringParams = new StringEntity(params.toString());
client.post(getApplicationContext(), requestAddress, stringParams, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "onFailure: error during creating event " + responseString,throwable );
Toast.makeText(getBaseContext(),"Error during creating event",Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(getBaseContext(),"Successfully create event",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), EventListActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
Log.e(TAG, "createEvent: error during creating event", e);
}
}
Check parameters and base url, use volley or retrofit library to Post request.
I m trying to post request like below response and getting the error {"message":"Model does not have field 'objects"'}
{
"num_results": 20,
"objects": [
{
"agent": "LAPTOP_01",
"bluetooth_id": "33:22:55:44:FF:AA",
"created_at": "2017-09-05T18:02:00",
"device_name": "android_name",
"id": 1,
"location": "gps_location_info",
"name": "LAPTOP_01",
"raw": "['additional','info','goes','here']"
}
],
"page": 1,
"total_pages": 2
}
and here is my code where i posting json string
AsyncHttpClient client = new AsyncHttpClient();
String someData="{\"objects\": [{\"agent\": \"tsetLappy\", \"bluetooth_id\": \"33:25:55:44:FF:AA\", \"created_at\": \"2017-09-05:02:00\", \"device_name\": \"android_test\", \"location\": \"gps_info\", \"name\": \"testlappy\", \"raw\": \"['addl','inf','ges','hee']\"}]}";
StringEntity entity = new StringEntity(someData);
client.post(MainActivity.this, "http://impero-dannyfast.rhcloud.com/api/agents", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
status.setText("Status: Posted Successfully!");
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
status.setText("Status: Error in Sending Data!"+errorResponse);
}
});
Please take a minute to help if you know about this error ...
Thanks
JSONObject obj = new JSONObject();
try
{
obj .put("num_results", your_value);
obj .put("page", your_value);
obj .put("pages", your_value);
JSONArray jarray = new JSONArray();
JSONObject objects_obj = new JSONObject();
objects_obj .put("agent", your_value);
....
.
.
.
jarray.put(objects_obj);
obj.put("objects",jarray);
} catch (JSONException e) {
e.printStackTrace();
}
//now pass this obj in request
Try this:
ByteArrayEntity entity = null;
try {
String someData="{\"objects\": [{\"agent\": \"tsetLappy\", \"bluetooth_id\": \"33:25:55:44:FF:AA\", \"created_at\": \"2017-09-05:02:00\", \"device_name\": \"android_test\", \"location\": \"gps_info\", \"name\": \"testlappy\", \"raw\": \"['addl','inf','ges','hee']\"}]}";
entity = new ByteArrayEntity(someData.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
client.post(context, requestUrl, entity, "application/json", new JsonHttpResponseHandler() {
}
if the above doesn't work for you try to remove all "\" from your json string
Check json Post request on Postman , if you getting same error then ask your api developer for exact Json Post format or tell them to check what he getting on back-end from Post. because this error message are showing from your server side.
I use Loop j for fetching data from server in my app. But it always fetch the old response . I test my api on postman and gets the latest response from server.
If any one know how to clear the loop j old response from cache?
Here is my code
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://bnailsusa.com/app_api/getView.php?serviceprovider", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) {
Log.d("Tag:", String.valueOf(response));
try {
for (int i=0;i<=response.length();i++){
//region Fetching
JSONObject index=response.getJSONObject(i);
String name=index.getString("Name");
String spid=index.getString("spid");
String Photo=index.getString("PHOTO");
//endregion
//region Storing
names.add(name);
SPID.add(spid);
images.add(Photo);
Log.d("Tag:ar", String.valueOf(names));
//endregion
}
} catch (JSONException e) {
e.printStackTrace();
}
ProvidersAdapter booksAdapter = new ProvidersAdapter(SelectServiceProvider.this, names,images);
gridView.setAdapter(booksAdapter);
}
public void onFailure(int statusCode, cz.msebera.android.httpclient.entity.mime.Header[] headers, Throwable throwable, JSONObject errorResponse){
}
});
I'm developing a new Android app which allow the user to rate the content. The rate is sent thanks to an asynchronous request (POST) over HTTPS. Unfortunately, the request don't reach my webservice. When I took a look at the log access log, the URL is truncated. You can find below the relevant code.
private static AsyncHttpClient getClient()
{
if(client == null)
{
client = new AsyncHttpClient(true, 80, 443);
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpClient().getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
}
return client;
}
public static void createComment(int idArticle, String content, final Context context, final Callback callback)
{
final User currentUser = RealmManager.getUser();
RequestParams paramsPost = new RequestParams();
paramsPost.put("id_article", idArticle);
paramsPost.put("id_utilisateur", currentUser.getId());
paramsPost.put("content", content);
HashMap<String, String> paramsGet = getDefaultParams(context, currentUser, "webservices.createCommentaire");
getClient().post(createGetURL(currentUser.getURL(), paramsGet), paramsPost, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response)
{
callback.onSuccess(/*..*/);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e)
{
callback.onFailure(/*..*/);
}
});
}
When I put a breakpoint and examine the request, it looks like :
https://api.webservices.com/index.php?option=webservices&app_version=2.0&task=createCommentaire&token=XXXXXXXXXXXX&version=v2&format=raw
But, in the access log, the URL is truncated after "?" :
POST - https://api.webservices.com/index.php?
Consequently, I got in the response the HTML of the index.php which I can't parse in JSON.
Thank you in advance for your help.
I have two suggestion for you.
Use from UrlEncoder.encode("") method for every part of your parameters
Do not use query string parameters for post data to server.
Trying to upload a file with params using loopj.
im trying to get file from Request.Files and params from Request.Form["create"]
but it is not uploading to the server.
Android Post method
try {
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.add("create", regString);
AsyncHttpClient client = new AsyncHttpClient();
client.post(createTeamURL, params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} catch (Exception e) {
Log.e("createTeamPreStep", e.getMessage());
}
My Web Api c# method
[HttpPost]
public async Task<string> CreateUHS()
{
var resultString = "";
foreach(HttpPostedFileBase s in Request.Files)
{
var a=s;
}
String sdf = Request.Form["create"];
}
You need to use put for string args.
please find the below both server and client methods.
and one more thing im really worried about your naming variable. its bad. please change it. Happy coding.
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.put("create", regString);
Server (Web api)
[HttpPost]
public async Task<string> CreateUHS()
{
var file=Request.Files[0];
String otherArg = Request.Form["create"];
}