如何在Laravel中返回Content type?

时间:2019-10-07 13:16:42

标签: java laravel laravel-5

我正在尝试将Laravel应用程序用作Android Studio项目。

我正在尝试从Java发送httpsrequest,如何返回响应?

就像我们在PHP中使用的那样,在标头oh .php文件中以header('Content-Type: application/json');的形式将响应作为JSON返回,消息为:

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

所以在laravel中,我试图将响应返回为:

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

但是它不起作用

在我的Java文件JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

那我该怎么做?

编辑:这就是我从.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
}}}

因此,当我使用http://website.com/test.phptest.php`

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

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

及其完美运行

但是,当我尝试从laravel控制器return response json运行时,它无法正常工作..

2 个答案:

答案 0 :(得分:2)

将标头作为第三个参数传递给响应助手

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

结果

enter image description here

您还可以像这样指示响应为JSON

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

我希望这对您有帮助

答案 1 :(得分:0)

使用return response()->json(['success'=>1]);时,您不需要将内容类型设置为'application/json'。方法json()将自动执行此操作。

如果您仍未获得正确的响应标头,则可能是由于您的自定义/修改的中间件之一设置了'Content-Type'标头。