【问题标题】:Error posting JSONObject using Volley android studio使用 Volley android studio 发布 JSONObject 时出错
【发布时间】:2020-10-07 13:27:22
【问题描述】:

我正在使用 Volley 发送 JSONObject,但我得到: java.lang.string 类型的值

谁知道问题出在哪里?!

这是我的java代码:

final JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("siteName", "example.com");
        jsonObject.put("field", "android");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        textView.setText(response.getString("websiteInfo"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(JsonActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

            Volley.newRequestQueue(JsonActivity.this).add(objectRequest);
        }
    });

这是我的 php 代码:

    <?php 
$json = file_get_contents('php://input');

$obj = json_decode($json);

$website = $obj->{'siteName'};

$field = $obj->{'field'};

$output ='';

$output->websiteInfo = $website.$field;

$jsonObject=json_encode($output);

echo $jsonObject;
?>

【问题讨论】:

    标签: java android json android-studio android-volley


    【解决方案1】:

    您将参数作为 JSONObject 传递。您应该重写 getParams 方法并传递您的参数..

    请查看博客以供参考:Android Volley Tutorial – Making HTTP GET, POST, PUT

    【讨论】:

    • 您好,谢谢。我试过但没有用。我尝试了很多方法!发送 JSONObject,发送字符串请求,我也尝试了很多 php 代码。在互联网上搜索了几天并尝试了所有方法,最后完全糊涂了,仍然不起作用...
    • 你可以发布你的 api 和 params 而不是这些 php 代码
    • 我发现问题出在哪里,接收到的值显示在我的应用程序中,但现在新的问题是 file_get_contents 返回 null ...难道没有其他方法可以在 php 中接收数据吗?
    【解决方案2】:

    这是解析错误。确保您的服务器返回类似这样的内容

    { "websiteInfo":"这是一个健康网站" }

    【讨论】:

    • 您好,谢谢,这可能是因为我使用的是本地主机吗?还是没关系?
    • 不,无论您使用本地主机还是实时服务器都没有关系。为了检查您的服务器返回的内容是什么,请使用邮递员。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 2016-09-30
    • 2019-07-09
    • 2018-12-17
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多