简体   繁体   中英

Volley POST string request unexpected error 500

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

Error 500 means there is problem in server code. Please check code written at server side. Thank you.

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.

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在此处输入图片说明

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.

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

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.

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.

Remove below line from your server-side code and check

echo $jsonformat=json_encode($companyData);

and the same is not working on postman also

在此输入图像描述

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

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

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

@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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM