Getting statusCode of 400 from GET - android

I am trying to do a get from the API, but it returns a 400, I have tried putting my local IP and putting 10.0.2.2, but he has continued to do the same, in the Event Log shows me this too: Emulator: CANNOT TRANSLATE guest DNS ip.From the PostMan I get the JSON back correctly so I do not think the problem is in the API
This is where I do everything
public void PendingTrajects(){
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://ip:port/api/trajectes";
client.get(this, URL, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
Toast.makeText(PendingTrajectRecyclerView.this, "Carregant...", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray Usuaris = new JSONArray();
JSONArray trajectes = new JSONArray();
String Nom = null;
String strResponseBody = new String(responseBody);
try {
//Usuari = new JSONArray(strResponseBody);
trajectes = new JSONArray(strResponseBody);
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
try {
for(int i = 0; i < trajectes.length(); i++){
JSONObject trajecte = trajectes.getJSONObject(i);
JSONArray realitzas = trajecte.getJSONArray("realitzas");
for(int j = 0; j < realitzas.length(); j++){
JSONObject realitza = realitzas.getJSONObject(j);
JSONObject usuari = realitza.getJSONObject("usuari");
Log.d("xd", ""+usuari.getString("name"));
}
}
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió ONFailure", Toast.LENGTH_SHORT).show();
Log.d("Error",""+statusCode);
}
});

400 BAD REQUEST
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
You should DEBUG your Application. Check your parameters.
Add a Break-point here
String URL = "http://ip:port/api/trajectes";
Actually server could not understand the request due to invalid syntax.

Related

Recyclerview inside another recyclerview adapter is not showing the item related items

I am working on an Android app.
There is a recyclerview that shows user messages, and there is another recyclerview in the adapter from first recyclerview that shows responses from users to the messages.
It is working but not as I want.
The responses shown at each message are not always the responses related to the message.
For example, at message #3, there are shown the responses to message #3, at message #2 there are shown the responses to message #3 and #2, at message #1 there are shown the responses to message #3, #2 and #1.
After refreshing the view, this can be different, the responses shown may be different.
This is the piece of code inside the adapter that manages the responses recyclerview;
//respuestas
holder.recyclerViewPosts.setHasFixedSize(true);
holder.recyclerViewlayoutManager = new LinearLayoutManager(context);
holder.recyclerViewPosts.setLayoutManager(holder.recyclerViewlayoutManager);
subjectsList = new ArrayList<>();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("origen", subjects.get(position).id_mensaje_chat);
params.put("rnd", getSaltString());
client.get(HTTP_JSON_URL, params, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
// called when response HTTP status is "200 OK"
Log.d("RES SUVJETC","respuesta chat "+res);
try {
JSONArray jsonArray = new JSONArray(res);
for(int i = 0; i<jsonArray.length(); i++) {
MensajesRespuestaChat GetDataAdapter2 = new MensajesRespuestaChat();
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
GetDataAdapter2.setid_respuesta(json.getString("id_respuesta"));
GetDataAdapter2.setemisor(json.getString("emisor"));
GetDataAdapter2.settexto(json.getString("texto"));
GetDataAdapter2.setfecha(json.getString("fecha"));
GetDataAdapter2.setorigen(json.getString("origen"));
GetDataAdapter2.setnombre(json.getString("nombre"));
GetDataAdapter2.setapellidos(json.getString("apellidos"));
} catch (JSONException e) {
e.printStackTrace();
}
subjectsList.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewChatRespuestaCardViewAdapter(subjectsList, context);
holder.recyclerViewPosts.setAdapter(recyclerViewadapter);
Integer num_mensajes = subjectsList.size();
if (num_mensajes == 0){
}
if (num_mensajes > 0){
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
}
);
Maybe you can find the reason for that issue there.
If you need further pieces of code, I can put them here, no problem.

Loop j always fetch previous response , not fetching the latest one

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

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.

AndroidHttpAsync not working at oncreate method

Whenever I use AsyncHttpClient in onCreate(Bundle savedInstanceState), onSuccess() method never used.
I put a break point, than debug... Never visit to break point if the break point is in the onSuccess() method, but when I put a button, after button click, it works?
I need to get values in onCreate() methods...
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
Of course, i can share my activity code
public class TestActivity extends Activity{
JSONArray arr = null;
String[] etkinlikAdlari;
String eposta;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down_temp);
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
}
}

eror when parsing json android no data when run

This is my code how i use to load data with json..
client.get(URL, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
if (!obj.getBoolean("error")) {
JSONArray cest = obj.getJSONArray("list");
String z = "";
if (cest != null) {
int array = cest.length();
mDetail = new ArrayList<OrderItem>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateOrder = new Date();
for (int i = 0; i < array; i++) {
try {
dateOrder = formatter.parse(cest.getJSONObject(i).getString("OrderDate"));
} catch (ParseException e) {}
mDetail.add(new OrderDetailsInfo(UUID.fromString(cest.getJSONObject(i).getString("OrderID"))
, dateOrder,
cest.getJSONObject(i).getString("BrancId"),
cest.getJSONObject(i).getString("DCBranchID"),
cest.getJSONObject(i).getString("OrderDocNo"),
cest.getJSONObject(i).getString("SubdealerID"),
cest.getJSONObject(i).getString("DocOrderNo"),
cest.getJSONObject(i).getString("OrderDocNoAlt"),
cest.getJSONObject(i).getString("SalesChannelID"),
cest.getJSONObject(i).getString("MarketingProgramID"),
cest.getJSONObject(i).getString("MDMarketingProgramID"),
cest.getJSONObject(i).getString("PriceListID")));
}
OrderDetailsAdapter adapter = new OrderDetailsAdapter(getActivity(), mDetail);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), "Refreshed: " + cest.length(), Toast.LENGTH_LONG).show();
} //if (cast != null) {
} //if (!obj.getBoolean("error")) {
} catch (JSONException e) {
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject errorResponse) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
// Probable causes: no internet permission, no internet connection
Toast.makeText(getActivity().getApplicationContext(), "error: onFailure: " + e.toString(), Toast.LENGTH_LONG).show();
}
});
}
When i run this there no eror but the data cannot be load..
What wrong with my code.?
Somebody please help me..

Categories

Resources