Trying to create a simple movie showtime mobile app. I've used the this method before in another class and it works fine but for some reason in this current class I get a 404 error.
client.get(String.format(VIDEO_URL, 209112), new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Headers headers, JSON json) {
try {
JSONArray results = json.jsonObject.getJSONArray("results");
if(results.length() == 0){
return;
}
String youtubeKey = results.getJSONObject(0).getString("key");
} catch (JSONException e) {
Log.e("DetailActivity", "Failed to parse JSON", e);
}
}
#Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
System.out.println("On failure again " +statusCode + " response: " + response);
}
});
I have the dependency line for it in my gradle file as well.
implementation 'com.codepath.libraries:asynchttpclient:0.0.9'
This is the onFailure message I get
On failure again 404 response: {"status_code":34,"status_message":"The resource you requested could not be found."}
HTTP 404 error is a server-side error.
404 not found
The problem should be irrelevant to your android code. You may check if the url you are requesting really exists.
EDIT:
You may log the url and check whether the format is correct
Related
here my function code to post using volley
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CHECK_IN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError response) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders () {
Map<String, String> map = new HashMap<String, String>();
map.put("Content-Type", "application/json");
map.put("appid", appids);
map.put("timestamp", timestamps);
map.put("token", tokens);
map.put("signature", signatures);
return map;
}
};
}
I don't know what's wrong with my code, because of 2 days ago everything fine.
and when I tried to debug, error show like this
BasicNetwork.performRequest: Unexpected response code 500 for http://api/presence/check_in
can anyone help me, please? because I'm stuck and need help or reference to solve my error
thank you
HTTP code 500 is Internal Server Error. Read more here. It generally implies that server is not able to process the request and come up with a response. This means that the code for your application might be alright whereas the server might be encountering some issue processing the current request body. I see that you are sending String in your request body. One peculiar thing I noticed with sending String in request body is that, we also need to check if the String is null or not, better to to use .trim() method at the end of your string too, which will delete starting and trailing spaces. Something simple like not escaping single quotes ( ' ) for the field you are trying to insert onto the database at your server might cause this. So server side field validation and best practices like Prepared Statements is also crucial. If you are absolutely sure that your client end [android app] is alright, maybe the server is encountering some issue at the endpoint you are hitting.
Test your api with a rest client like POSTMAN or INSOMNIA to be absolutely sure that your server and api layer is working as intended. Good Luck
This page says that we can register a Listener to a volley request for handling errors:
https://developer.android.com/training/volley/simple
But it doesn't mention what kind of errors trigger this listener. Volley javadoc doesn't say anything about it either.
Specifically, will this listener be executed if a network error occurs.
I'm asking this because I've encountered an android code of the following form:
private void method() {
String URL = "";
final int[] status_code = new int[1];
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (status_code[0] == 200) {
// do something
} else {
// display toast
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// display toast
}
}) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
status_code[0] = response.statusCode;
return super.parseNetworkResponse(response);
}
};
// add request to queue
}
This code seems to suggest that the registered ErrorListener isn't called for network errors.
What are the conditions which cause the ErrorListener registered to a Volley request to be called
The ErrorListener is triggered for 4xx responses and 5xx responses I cannot tell what happens though for the 3xx redirection responses as it didn't happended to me.
Here is a list with all HTTP Response codes:
https://www.restapitutorial.com/httpstatuscodes.html
I'm not exactly privy to your entire code but poking through the Volley source code:
Response.java takes in VolleyError object
VolleyError references NetworkResponses in its use.
Inspecting NetworkResponses deals with mainly HTTP status codes.
Also I'd note that VolleyError extends Exception.
So I would say the call back method is triggered when an Exception is thrown and VolleyError deals with HTTP status codes.
I just call this statement
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Log.i(TAG, "onErrorResponse: " + context.getString(R.string.error_network_timeout));
} else if (error instanceof ServerError) {
Log.i(TAG, "onErrorResponse: " + context.getString(R.string.error_server));
} else if (error instanceof NetworkError) {
//toast or log your error
} else if (error instanceof ParseError) {
Log.i(TAG, "onErrorResponse: " + context.getString(R.string.parse_error));
} else {
Log.i(TAG, "onErrorResponse: Something went wrong ");
}
You don't need to find error code
I know for a fact the data I am sending in this is getting sent unlike my previous question where an exception was being thrown. I can successfully execute a request object using loopj async http client however i am unable to get my data from the php side and display it, the status code that gets displayed is 200 which means the request library is working. I have a felling it maybe a firewall issue but not sure how to bypass that? Any tips on how to resolve this from the php side would be much appreciated.
here is my code:
protected void PostData(final Integer Question_ID,Integer ResponseChosen_ID) throws IOException {
try{
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params1 = new RequestParams();
params1.put("Question_ID", Question_ID.toString());
params1.setUseJsonStreamer(true);
client.get("http://cce.swlgroup.com/SwlLogin.php/", params1, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
messageBox("Response Successful: ", "" + statusCode);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("Response",error.toString());
}
});
System.out.print(params1);
}
}
}
php code:
repo.php:
var_dump($_SERVER);
var_dump($_GET);
nothing is displayed here, im also not sure now what i am trying to do is even possible with the built in library and now a third party library.
I'm using GWT and creating a HTTP request but I'm having issues accessing the file from the production version, even though it's working fine in development. My main program has the following for the request on the client side.
static final String dataURL = GWT.getModuleBaseURL() + "interpretData";
public void onModuleLoad() {
requestData(dataURL, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
RootPanel.get(holderId).add(new Label(error + ": Asynchronous call failed - " + caught.getLocalizedMessage()));
return;
}
public void onSuccess(String JSON){
try{
// code executed on success
} catch (Exception e) {
RootPanel.get(holderId).add(new Label(error + ": " + e.getMessage()));
return;
}
}
});
}
public static void requestData(final String url, final AsyncCallback<String> callback) {
// create a request for the xml data on the server
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
builder.setCallback(new RequestCallback() {
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
public void onResponseReceived(Request request, Response response) {
try {
final int responseCode = response.getStatusCode() / 100;
if (url.startsWith("file:/") || (responseCode == 2) || (responseCode == 0)){
callback.onSuccess(response.getText());
} else {
callback.onFailure(new IllegalStateException(" Http Error: #" + response.getStatusCode() + " - " + response.getStatusText()));
}
} catch (Throwable e) {
callback.onFailure(e);
}
}
});
On the server side, I have:
public class interpretData extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("application/json");
// code to return a String
}
Finally, my XML file has the following in it:
<servlet>
<servlet-name>interpretData</servlet-name>
<servlet-class>com.gmod.caeli.server.interpretData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>interpretData</servlet-name>
<url-pattern>/caeli/interpretData</url-pattern>
</servlet-mapping>
In the end, I can access the file from: http://127.0.0.1:8888/caeli/interpretData so the development version is completely fine, but I don't know how to get it to work in production (the URL I'm calling for production is file:///~/workspace/Caeli/war/caeli/interpretData) I've searched for examples, but I haven't found any clues to what I'm doing wrong. I tried using setting it up with tomcat and I got a 404 error there too. I feel like I'm missing something small, so hopefully this is enough information for someone to notice something wrong.
From my experience and research, the URL that your attempting to request in production (file:///...) cannot be requested by the web browser via an Ajax call, anchor tag, javascript etc. It might be a little confusing/misleading as you can enter that URL into your browser manually and get the expected result, however this local resource request is not allowed by the browser.
I am trying to send image files from my android app to a back end server. On Postman, images are sent and response code:200 is received.
However, trying to send images from my android app using retrofit, I keep receiving response code:500 Internal Server Error. Here is my code:
public interface RetrofitInterface {
#Multipart
#POST("uploads/addImage")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part image);
}
The NetworkClient
public class NetworkClient {
private static Retrofit retrofit;
public static Retrofit getRetrofit(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS).build();
if(retrofit == null){
String BASE_URL = "https://addimage.herokuapp.com/";
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).
addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
}
return retrofit;
}
}
And then the call
private void uploadImage(Uri imageUri){
File file = new File(imageUri.toString());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", "image.jpg", requestBody);
Retrofit retrofit = NetworkClient.getRetrofit();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.uploadImage(body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
Log.d("UploadImage", "Yeepee!!! = "+response.message());
}else Log.d("UploadImage", "Response failure = "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (t instanceof SocketTimeoutException) {
// "Connection Timeout";
Log.e("UploadImage", "Connection Timeout");
} else if (t instanceof IOException) {
// "Timeout";
Log.e("UploadImage", "Timeout");
} else {
//Call was cancelled by user
if(call.isCanceled()) {
Log.e("UploadImage", "Call was cancelled forcefully");
} else {
//Generic error handling
Log.e("UploadImage", "Network Error :: " + t.getLocalizedMessage());
}
}
}
});
}
I am not sure if it's a server error since images upload successfully from Postman. I am very confused and I am not sure what I am doing wrong.
According to your Postmen screen shot there is no key for image file can you try like below
remove this line
MultipartBody.Part body = MultipartBody.Part.createFormData("file", "image.jpg", requestBody);
And add this one
MultipartBody.Part body = MultipartBody.Part.createFormData("", "image.jpg", requestBody);
Generally 500 Internal Server error means there is something wrong in the server, but if the Postman is giving 200 that means the server part is OK, there's something wrong in your code.
try changing this line
File file = new File(imageUri.toString());
to this
File file = new File(imageUri.path);
And also make sure that the key name you used is same as the response key name
Thank you all for your responses. I have been able to resolve and it turned out to be a conflict between my request body and what the server was expecting.
For my case, I was sending a different mime-type(a .jpg), where the server developer made the server look for .jpeg and .png.
This was how I got to see the error and resolve the conflict.
Call<ResponseBody> call = retrofitInterface.uploadImage(body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
Log.d("UploadImage", "Yeepee!!! = "+response.message());
}else {
Log.d("UploadImage", "Response failure = "+response.message());
try {
Log.d("UploadImage", "Response failure = "+response.errorBody().string());
} catch (IOException e) {
Log.d("UploadImage", "IOException = "+e.getMessage());
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (t instanceof SocketTimeoutException) {
// "Connection Timeout";
Log.e("UploadImage", "Connection Timeout");
} else if (t instanceof IOException) {
// "Timeout";
Log.e("UploadImage", "Timeout");
} else {
//Call was cancelled by user
if(call.isCanceled()) {
Log.e("UploadImage", "Call was cancelled forcefully");
} else {
//Generic error handling
Log.e("UploadImage", "Network Error :: " + t.getLocalizedMessage());
}
}
}
});
The response.errorBody().string() got the error message from the server and I was able to resolve the conflict.