Android: AsyncHttpClient reponse goes to OnFailure - android

I am trying to parse data from URL. The URL that i test in mobile browser its working fine. I am trying to parse data by AsyncHttpClient .after exection its going to onFailure method.
in dependencies add
compile 'com.loopj.android:android-async-http:1.4.9'
and I import
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import cz.msebera.android.httpclient.Header;
..
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
pg1.dismiss();
String jsonStr = new String(responseBody, "UTF-8");
Log.e("Tag ","jsonStr "+jsonStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
pg1.dismiss();
Log.e("Tag ","fetch feeds fail");
}
});
The URL is in GET method
can any one please help me to resolve this issue

Just print responseBody in onFailure() method. if it is timeoutexception; then you can set client.setTimeout(30000); before client.get().
OR
check your url; if it its giving response in browser or not and also check keys and values. that may be server is not giving you any response.

I am doing same thing using inner class extends AsncyTask.
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
data = ((new WeatherHttpClient()).getWeatherData(params[0], params[1]));
Log.d("DATA", data);
try {
weathers = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
inside WeatherHttpClient class I get data using URL with HttpUrlConnection.

Related

Code doesn't work when server response the request

Recently I'm learning the request and response between server and android .
I try to update a JSON file when server responses but I'm failed. the update code doesn't work.
the server code like this:after the code"JSONArray"doesn't work but i don't know why.
public class AndroidServerServlet extends HttpServlet {
private static final long serialVersionUID = 6792396567928634227L;
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String newPassword = request.getParameter("newpassword");
PrintWriter printWriter = response.getWriter();
printWriter.print("hello android, password changed");
printWriter.flush();
printWriter.close();
System.out.println(username+"\n"+newPassword);
ChangePassword(username , newPassword);
}
private void ChangePassword(String username , String password){
try {
InputStream in = AndroidServerServlet.class
.getClassLoader().getResourceAsStream("/1.json");
Scanner scanner = new Scanner(in, "UTF-8"); //InputStream → String
String jsonData = scanner.useDelimiter("\\A").next();
System.out.println(jsonData);
scanner.close();
JSONArray jsonArray = new JSONArray(jsonData);
for(int i = 0;i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
if(username.equals(object.getString("username")))
object.put("password",password);
}
System.out.println(jsonData);
in.close();
}catch (Exception e){
System.out.print("Exception\n");
}
}
}
the android code like this:(surbmit is a button)
surbmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestParams requestParams = new RequestParams();
requestParams.add("newpassword", "newpassword");
requestParams.add("username","test1");
new AsyncHttpClient().post("http://10.0.2.2:8080/AndroidServerServlet", requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "server doesn't response", Toast.LENGTH_LONG).show();
}
});
}
});
and the json file is this:
[{"username":"test1","password":"password1"},
{"username":"test2","password":"password2"},
{"username":"test3","password":"password3"}]
When I debug the server code,I found a ERROR:java.long.NoClassDefFoundError:org/json/JSONArray.but I have alerady add that jar in the project,why the error comming?
BTW:I use IntelliJ IDEA + MAVEN + Tomcat to build my server.
the error report:
java.lang.NoClassDefFoundError: org/json/JSONArray
at AndroidServerServlet.ChangePassword(AndroidServerServlet.java:41)
at AndroidServerServlet.doPost(AndroidServerServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I tried to delete the jar I had added and the wrong report is still same as top,proved that I didn't add the jar really,but how can I add it?
May I suggest using HttpUrlConnection instead of ServletRequest/Response, Scanner, etc ...
Please check this link:https://developer.android.com/reference/java/net/HttpURLConnection.html
You'll find a sample in the Posting Content section.

Android - asynchttpclient send back resul from onSuccess or onFailure

Hy!
I want to make some http calls to a restserver from my android client. I created a class for rest calls.
I followed the http://loopj.com/android-async-http/ description:
My question is that how can I send back anything from onSucces() method? For example I have the following function:
public class RestController {
public String getName() throws JSONException {
TwitterRestClient.get(url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
String name;
try {
name = response.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
How can I return the name to getName function?
function () {
...
String name = restController.getName();
...
do something with the name
Thank you very much!
I will apreciate any kind of help!

Loopj - Uploading Files with RequestParams c# .net

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"];
}

Get JSON data from LoopJ AndroidAsyncHttp

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();
}
}

onSuccess - Asynchronous Http Client

I'm using the Android Asynchronous Http Client. My code looks like this and is working fine.
DataUtil.post("RegisterUser", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String answer) {
// initialize variables
JSONObject json = new JSONObject();
String message = null;
try {
// turn string into JSONObject
json = new JSONObject(answer);
message = json.getString("message");
} catch (JSONException e) {
Log.e("ERROR", e.getMessage());
}
// registration was successful
if (message.equals("success")) {
// forward to login page
} else {
// error
}
}
});
I implemented a static HTTP Client. My server returns this JSON data {"message":"success"}. I do not want to treat it as a String and cast it back to JSON. But when I change it to public void onSuccess(JSONObject answer) eclipse tells me
The method onSuccess(JSONObject) of type new
AsyncHttpResponseHandler(){} must override or implement a supertype
method
The correct method signature would be this public void onSuccess(int statusCode, Header[] headers, JSONObject response) or any of the other available methods in the JsonHttpResponseHandler class

Categories

Resources