简体   繁体   中英

How is it possible to retrieve "String response" from php via retrofit in android?

I need to insert some data from my android app into database via retrofit , whose part of interface is something like below:

@FormUrlEncoded
    @POST("*****")
    Call<model> insertChordReq(@FieldMap Map<String, String> fields);

The retrofit sends data to a php file from @POST annotation. The php codes are as the following:

<?php

$sN = $_REQUEST['sN'];
$siN = $_REQUEST['siN'];
$soT = $_REQUEST['soT'];


try {
    $connection = new PDO("mysql:host=******;dbname=*******", "******", "******");
    $connection->exec('set names utf8');
    $insertQuery = "INSERT INTO table (sN, siN, soT) VALUES ('$sN', '$siN', '$soT')";
    if ($connection->exec($insertQuery)){
        echo 'درخواست شما با موفقیت ثبت گردید';
    }else{
        echo 'error';
    }
} catch (PDOException $e) {
    echo $e;
}

Then I want to show the String response, echo 'درخواست شما با موفقیت ثبت گردید'; , in my app; but the problem is retrofit doesn't return it as a response. Instead, I get an error through onFailure :

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

I have to mention that the insertion process into database is done successfully , but I need to get the specified response.

Is there any way to get the string through the retrofit?

Is there any way to turn the string into json and then get it through the retrofit?

I've searched the existing questions in stackOverFlow. Unfortunately I didn't find the exact solution.

You have to do some modifications to your PHP file as well as the android receiver part as below. echo just outputs the string from the php file, but your retrofit module expects a json emit. JSON_UNESCAPED_UNICODE is added to support the Non-english support. You should also consider keeping the same json format in your retrofit API interface, too. Here I have added String as the same response format, change it at your convenience....

EDITED

 echo json_encode('درخواست شما با موفقیت ثبت گردید',JSON_UNESCAPED_UNICODE);

in your android code

@FormUrlEncoded
    @POST("*****")
    Call<String> insertChordReq(@FieldMap Map<String, String> fields);

Also, I found that this issue can be solved by changing the call<type> . Using Void instead of model returns a response (not a failure), which will help to handle the UI/UX with some conditions on onResponse :

@FormUrlEncoded
    @POST("*****")
    Call<Void> insertChordReq(@FieldMap Map<String, String> fields);

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