简体   繁体   中英

How can i return with Content type in laravel?

I am trying to use a Laravel application as an Android Studio project.

I am trying to send a httpsrequest from Java, how do I return a response?

Like we use in PHP to return response as JSON as header('Content-Type: application/json'); at the header oh.php file and the message as:

$response["message"] = "Signin succsessfully done."; echo json_encode($response);

so in laravel i am trying to return response as:

return response()->json(['success'=>1]) ->header('Content-Type', 'application/json');

but it's not working

in my Java file JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

So How do i do this?

edit: this is how i am calling from.java

  JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

        // Check your log cat for JSON reponse

        try {
            // Checking for SUCCESS TAG
            success = json.getInt(TAG_SUCCESS);`
 } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Rjn_login_error"+e.getMessage());
        }






/**
         * After completing background task Dismiss the progress dialog
         * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /*
                  Updating parsed JSON data into ListView
                 */
                if (success == 1) {
                    // jsonarray found
}}}

So when i am using calling the url as http://website.com/test.php and in the test.php `

    $response["success"] = 1;
        $response["message"] = "Signin succsessfully done.";

        // echoing JSON response
        echo json_encode($response);

and its working perfactly

But when i tried to return response json from laravel controller it's not working..

Pass headers as third param to response helper

return response([
    'status' => 'success'
], 200, ['Content-Type => application/json']);

Results in

在此处输入图像描述

You can also instruct the response to be JSON like so

return response()->json([
    'status' => 'success'
], 200);

I hope this helps

When you use return response()->json(['success'=>1]); you dont need to set the content type to 'application/json' . The method json() will do it automatically.

If you're still not getting the right response header, it might be due to one of your custom/modified middleware that is setting the 'Content-Type' header.

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