发送带有改型的参数后,我无法从ResponseBody获得字符串消息

时间:2018-09-28 13:08:41

标签: android retrofit

我在改装时遇到问题。

使用@post发送参数:

 @FormUrlEncoded
@POST("sendSms.php")
Call<ResponseBody> sendValidationCode(@Field("phone") String phoneNo);

sendSms.php:

<?php
...
try {


date_default_timezone_set("Asia/Tehran");


$APIKey = "**************";
$SecretKey = "***************";
$LineNumber = "***************";
$text = rand(1000, 9999);
$mobile = $_POST["phone"];

$MobileNumbers = array($mobile);


$Messages = array($text);

@$SendDateTime = date("Y-m-d") . "T" . date("H:i:s");
$SmsIR_SendMessage = new SmsIR_SendMessage($APIKey, $SecretKey, $LineNumber);
$SendMessage = $SmsIR_SendMessage->SendMessage($MobileNumbers, $Messages, $SendDateTime);

echo $SendMessage


} catch (Exeption $e) {
echo 'Error SendMessage : ' . $e->getMessage();
}
?>

代码:

 ApiService service = ApiClient.getClient().create(ApiService.class);

                        Call<ResponseBody> call = service.sendValidationCode(edtPhoneNo.getText().toString());

                       call.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                                String message=response.body().toString();//.trim();

                                Toast.makeText(ActivityMain.this, message, Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                Toast.makeText(ActivityMain.this, t.toString() + "", Toast.LENGTH_SHORT).show();
                            }
                        });

此代码可以正常工作。并且将4位数代码发送到电话号码,但是消息“发送成功”。不与Toast response.body().toString();

一起显示

我试试这个:

<?php
    $mobile = $_Post["phone"];
    echo "ok";
?>

ok不能与Toast response.body().toString();一起显示并显示okhttp3.ResponseBody$1@e7afd80

2 个答案:

答案 0 :(得分:2)

toString()方法将打印responseBody对象,而不是您要查找的实际String响应。

这就是为什么要在烤面包中加入okhttp3.ResponseBody$1@e7afd80的原因。

尝试使用response.body().string();而不是response.body().toString()

答案 1 :(得分:0)

更改此

String message=response.body().toString();

String message=response.toString();

更好的方法是在JSONObject中添加响应

使用JSON

    try {
    JSONObject jobj = new JSONObject(response);
Log.d("===","jobj   "+jobj .toString());


    }
     catch (JSONException e1) {
             e1.printStackTrace();
    }