Volley POST string request unexpected error 500
Asked Answered
M

11

10

I am using Volley library in my project and getting Unexpected response code 500 as response.

I have searched stackoverflow thoroughly and still unable to find solution that works.

Following is my code for making GET string request

        val API = "http://squadtechsolution.com/android/v1/allcompany.php"
        val requestQueue = Volley.newRequestQueue(mActivity)
        val stringRequest = StringRequest(
            Request.Method.GET,
            API,
            Response.Listener { response ->
                Log.i("dxdiag", response)
                mView.onFetchHttpDataResult(true)
                Toast.makeText(context, response, Toast.LENGTH_LONG).show()
            },
            Response.ErrorListener { error ->
                Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show()
                Log.i("dxdiag", error.printStackTrace().toString())
                mView.onFetchHttpDataResult(false)
            })
        requestQueue.add(stringRequest)

Following is the stacktrace

2019-09-03 17:15:53.237 3308-3892/com.squadtechs.markhor.foodapp 
E/Volley: [194] BasicNetwork.performRequest: Unexpected response code 
500 for 
http://squadtechsolution.com/android/v1/allcompany.php
2019-09-03 17:15:53.243 3308-3351/com.squadtechs.markhor.foodapp 
D/EGL_emulation: eglMakeCurrent: 0xa7d84180: ver 2 0 (tinfo 
0xa7d832b0)
2019-09-03 17:15:53.256 3308-3308/com.squadtechs.markhor.foodapp 
W/System.err: com.android.volley.ServerError
2019-09-03 17:15:53.257 3308-3308/com.squadtechs.markhor.foodapp 
W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:205)2019-09-03 17:15:53.257 3308-3308/com.squadtechs.markhor.foodapp W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)2019-09-03 17:15:53.257 3308-3308/com.squadtechs.markhor.foodapp W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)2019-09-03 17:15:53.257 3308-3308/com.squadtechs.markhor.foodapp W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)

Following is PHP code that I wrote on server side:

<?php
    require 'db.php';

    $sql = "SELECT * FROM `company_profile`";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        $id=$row['id']; 

        $company_name=$row['company_name'];
        $cuisine=$row['cuisine'];
        $conpany_phone=$row['conpany_phone'];
        $company_description=$row['company_description']; 
        $company_logo=$row['company_logo'];
        $company_type=$row['company_type'];
        $delivery_type=$row['delivery_type'];
        $delivery_range=$row['delivery_range']; 
        $delivery_fee=$row['delivery_fee'];
        $delivery_pickupinfo=$row['delivery_pickupinfo'];
        $address=$row['address'];

        $companyData[] = array('id'=> $id,'company_name'=> 
        $company_name,'cuisine'=> $cuisine,'conpany_phone'=> 
        $conpany_phone,'company_description'=> 
        $company_description,'company_logo'=> $company_logo,'company_type'=> 
        $company_type,'delivery_type'=> $delivery_type,'delivery_range'=> 
        $delivery_range,'delivery_fee'=> 
        $delivery_fee,'delivery_pickupinfo'=> $delivery_pickupinfo,'address'=> $address);   
    }
    echo $jsonformat=json_encode($companyData);
    } else {
        echo "0 results";
    }
    $conn->close();
?>
Min answered 3/9, 2019 at 10:19 Comment(14)
make sure you are sending all params in requestVerena
Would you please share the Postman request screenshot with your question?Tropicalize
and where is the server-side code, that returns HTTP 500 ?? That an IDE update causes this is extremely unlikely.Saliva
@MartinZeitler here you go, I have added php code as wellMin
This does not match the URL logcat is showing.Saliva
Ooh sorry @MartinZeitler, I forgot to update logcate, let me edit that one as wellMin
You said that you want to send a POST request, but your code does a GET request.Rounce
Ooh..sorry..it is GET actuallyMin
please share the Generate Code Snippet value from postman by clicking the Code on the right hand side of the software.Rounce
Will do after I get back homeMin
got the chance to check the postman?Rounce
can you please explain where to find this option?Min
I'll ask you to follow a simple step to check the origin of the problem. Create a simple Android project with single Activity and check if it still returns Unexpected response code 500 as a response? I just checked your exact code it returns a response without a problem. And tell me your Volley version, please.Marje
Second option: To test whether it's because of the conversion problem not. Delete everything in your PHP file and replace with <?php // Declare an array $value = array( "name"=>"GFG", "email"=>"[email protected]"); // Use json_encode() function $json = json_encode($value); // Display the output echo($json); ?> if it doesn't throw an error, then you'll have to make changes in your PHP file to properly encode your responseMarje
S
1

I modified the code a bit and checked it in postman, it works fine.

I moved the JSON encode statment out of the if statement.

// output data of each row
while($row = $result->fetch_assoc()) {

    $id=$row['id']; 

    $company_name=$row['company_name'];
    $cuisine=$row['cuisine'];
    $conpany_phone=$row['conpany_phone'];
    $company_description=$row['company_description']; 
    $company_logo=$row['company_logo'];
    $company_type=$row['company_type'];
    $delivery_type=$row['delivery_type'];
    $delivery_range=$row['delivery_range']; 
    $delivery_fee=$row['delivery_fee'];
    $delivery_pickupinfo=$row['delivery_pickupinfo'];
    $address=$row['address'];

    $companyData[] = array('id'=> $id,'company_name'=> 
    $company_name,'cuisine'=> $cuisine,'conpany_phone'=> 
    $conpany_phone,'company_description'=> 
    $company_description,'company_logo'=> $company_logo,'company_type'=> 
    $company_type,'delivery_type'=> $delivery_type,'delivery_range'=> 
    $delivery_range,'delivery_fee'=> 
    $delivery_fee,'delivery_pickupinfo'=> $delivery_pickupinfo,'address'=> $address);   
}
echo $jsonformat=json_encode($companyData);

$conn->close();
Schumer answered 19/9, 2019 at 10:48 Comment(1)
great that it helpedSchumer
A
1

Remove below line from your server-side code and check

echo $jsonformat=json_encode($companyData);

and the same is not working on postman also

enter image description here

Antispasmodic answered 11/9, 2019 at 10:27 Comment(1)
let me check thisMin
X
1

HTTP status code 500 represents the internal server error, clearly states that you don't have any issue in client-side (here in your case Volly) but the issue is at server-side. Try debugging your server-side php code. the code is not properly executing and hence it's returning the 500 internal server error in Http response header. Volly just thrown the received header as an error.

If you are backend dev, you should try it first with REST Clients before integration with the mobile application. You can get it one from Here. Your API should be well tested and should be in a working state otherwise you will receive errors all the time.

Xena answered 11/9, 2019 at 10:36 Comment(10)
open your server directory and look for the .errorlog file, the error will be dumped there. can you post it here? because it's server-side error and I'm sure about it.Xena
I just noticed that postman also gives same error but in quite hidden mannerMin
you can post it here, or give me an error screen image, please. it would be best if you can post the .errorlog file from serverXena
I think missing any parameter while the response to client-side. response array data miss any parameter. check database too for valid entry in databaseAposiopesis
you can check here developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 you are missing something, but what did you miss? to find it out check the server-side code or post the log here. However, the php code you have posted is not complete code so it's difficult to find out the bug.Xena
I believe something is wrong with php code I wrote but as I am not a php developer, I can't actually debug it properly, would you be kind enough to look at my php code??Min
Sure, I'm pretty fluent with it. Please post the .php fileXena
@KiranManiya,Why you're insisting it's a backend problem when OP says backend operates properly :) ? Just post the given URL in Postman you'll get a response with 200 response code. I've tried it and got a proper response.Marje
@Marje the url was not working at that time I commented, eventually, the server throws 500 when it can't respond because of error.Xena
You're talking about 500 Internal Server Error OP's response is Unexpected response code 500 it happens in client level, not in server levelMarje
V
1

I have something First import the okhttp inside the Gradle dependency (Library). here is the documentation

https://square.github.io/okhttp/

After open the postman and click on the code menu enter image description here

As you can see below the send Button the code button is there. click it and select the java-> okhttp

copy the code and paste it inside android studio. it has 99.9 % chance it will work.

Veliavelick answered 16/9, 2019 at 8:31 Comment(1)
Thanks for answer but my project is bound to use VolleyMin
S
1

I modified the code a bit and checked it in postman, it works fine.

I moved the JSON encode statment out of the if statement.

// output data of each row
while($row = $result->fetch_assoc()) {

    $id=$row['id']; 

    $company_name=$row['company_name'];
    $cuisine=$row['cuisine'];
    $conpany_phone=$row['conpany_phone'];
    $company_description=$row['company_description']; 
    $company_logo=$row['company_logo'];
    $company_type=$row['company_type'];
    $delivery_type=$row['delivery_type'];
    $delivery_range=$row['delivery_range']; 
    $delivery_fee=$row['delivery_fee'];
    $delivery_pickupinfo=$row['delivery_pickupinfo'];
    $address=$row['address'];

    $companyData[] = array('id'=> $id,'company_name'=> 
    $company_name,'cuisine'=> $cuisine,'conpany_phone'=> 
    $conpany_phone,'company_description'=> 
    $company_description,'company_logo'=> $company_logo,'company_type'=> 
    $company_type,'delivery_type'=> $delivery_type,'delivery_range'=> 
    $delivery_range,'delivery_fee'=> 
    $delivery_fee,'delivery_pickupinfo'=> $delivery_pickupinfo,'address'=> $address);   
}
echo $jsonformat=json_encode($companyData);

$conn->close();
Schumer answered 19/9, 2019 at 10:48 Comment(1)
great that it helpedSchumer
C
0

This error "500" means serverside error.This errors occurs in these case:-

  1. May be wrong spell on the parameter or URLs
  2. Lack of Parameter.
  3. Or you are sending something that isn't accepted by Server.
  4. Also Check "http:/" or"https:/" on Urls.

Check these conditions.I have also faced same problem .APIs are working on Post Man but not working on devices using volley. Hope this may help you.

Conscript answered 11/9, 2019 at 10:1 Comment(9)
@MuhammadFaizan have check on the "Company_mobile" parameter if there any wrong?Conscript
@MuhammadFaizan your parameter is not accepting the Server. Please check your server accepting key at once.Conscript
I have changed my php file and removed all params, still nothingMin
@MuhammadFaizan Now,you have changed it in to GET Method.Then what are you getting error.Conscript
@MuhammadFaizan I have just intgrated your api in demo and its working fine at myside.Conscript
Same...I have updated logcat, you can read that is says error code 500 for urlMin
That is the issue, Postman is running the API normally but volley is throwing the errorMin
The error you're referring to is Internal server error, OP's error is Unexpected error that means the problem is in the client level, not from the server.Marje
@Marje Yes i am talking about Internal Server .Conscript
I
0

Please check if all params you are trying to send are the same which server is expecting. Also wrong or missing parameters return 500 Error. Reverify this param Company_mobile in your request. Hope this resolves your issue.

Imago answered 11/9, 2019 at 10:5 Comment(0)
A
0

HTTP Status Codes starting with 5 inform that the error is on server side. The code 500 is interpreted as Internal Server Error, to solve this you have to check what might cause it. It may be caused by a mistake in the code in that case you can open your error_log to see the error and act accordingly.

It can be caused by server features being unavailable momently like accessing the database or having many simultaneous opened connections that exceed the associated mysql resources.

Some other times, the error is not logged into the error_log file. If you use a cpanel, at the homepage, under Metrics tab open Errors and check according to the time you requested to the server. If you are not using cpanel look for a corresponding server log.

follow this Right mark Answer.. it may help you

How to deal with unexpected response 500 in Android

Aposiopesis answered 11/9, 2019 at 10:31 Comment(5)
let me check and I will let you knowMin
Right now I checked response it is giving 200 OK ResponseAposiopesis
just change your content type text/html to application/jsonAposiopesis
did but same response :'(Min
Everybody in this thread is talking about Internal server error, OP gets Unexpected response that means the problem is happening in a client not originating from the server.Marje
C
0

Check your db.php file and then see variable that return object of connection.

I see it should be $con->close() with one n not $conn->close() with double n

Circe answered 12/9, 2019 at 17:40 Comment(1)
While you have a good point, this should be a comment because while your right $conn should be $con it would not cause a 500 error because PHP will close the connection on its own after a timeout of not being used.Showcase
P
0

Try including in your php file :

header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

I am not familliar with Kotlin but it is working fine for me using Java , here is the code :

private void loadRecyclerViewData2(){
        URR_DATA="http://squadtechsolution.com/android/v1/allcompany.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                URR_DATA,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("****"+response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("***"+error.getMessage());                    }
                });
        requestQueue = Volley.newRequestQueue(Home.this);
        requestQueue.add(stringRequest);
    }

And i get the following output :

I/System.out: ****
    [{"id":"1","company_name":"ABC","cuisine":"QATAR","conpany_phone":"4535345","company_description":"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ","company_logo":"company_logo5d80bac690f2e.png","company_type":"Food","delivery_type":"yes","delivery_range":"55","delivery_fee":"","delivery_pickupinfo":"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, ","address":"33.58539655788556,71.43779296427965"}]
Petula answered 16/9, 2019 at 22:23 Comment(1)
@MuhammadFaizan Internet permission in your mafinest file ?Petula
J
0

@Muhammad Faizan ignore your doubts, the issue IS a 500 server error

THIS IS THE CAUSE

  • POSTMAN and VOLLEY are not the same
  • a) there is a bug in your PHP code or B) there is an environment setting that this exposes

TO DIAGNOSE A PHP ISSUE

and you need to open your error_log on php. Depending on your server this can be tricky to explain how so the other way is to change the php.ini to error_log to do this try this ON THE SERVER

(lifted from here deliberately)

/*This always works for me:*/

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/*However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:*/

display_errors = on
/*(if you don't have access to php.ini, then putting this line in .htaccess might work too):*/

php_flag display_errors 1

TO DIAGNOSE A ENVIRONMENT ISSUE ON SERVER

If the error_log yields nothing try the access_log. Why? Because it will probably show a different type of request has come in. and POSTMAN and VOLLEY are not the same

You need to look at your access_log too potentially and watch it in real time as you click postman then click the volley client

FACTS: (why we can be so sure)

My gut says you have an issue in a wrongly configured server. Believe it or not the access_log will help you the most if this is the case.

Regardless: There is clearly an issue between what you are putting into POSTMAN and what your volley client is sending - that is causing this.

Things I have seen cause this include:

  • It could be a SAME ORIGIN error.
  • It could be a INTERNAL SERVER REDIRECT issue.
  • It could be an imprecise forwarding of $_GET to $_POST (I have seen that issue on nginx)
  • It could be a bad path issue that is being mangled with no-redirect and lack of security.

but without telling us the platform or the server (Windows? Linux? nginx? php-fpm? apache? etc) we can't get to help you on those

Josiahjosias answered 18/9, 2019 at 8:20 Comment(3)
Thanks for your details explanation but as I am not a PHP developer, I can't completely understand everything, the PHP code above has been written by another person from freelance serviceMin
@MuhammadFaizan I suspected as much.. paste the code I gave you into the top of the <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); and watch what it returns in POSTMAN and VOLLEY - also if it is a server config issue (as I suspect).. try to get on the server and watch the access_logJosiahjosias
I will as a friend to do all this and will see if it works or notMin
V
0

I am posting another answer If it is still unsolved. In the postman copy all the headers like

.addHeader("content-type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "fa72f792-c9d3-7891-a544-f37f634f6ee1")

and put that in the volly params

Veliavelick answered 18/9, 2019 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.