简体   繁体   中英

cannot send a value and response with retrofit 2

I have a PHP file that receives data from Android and when I tested the PHP file from the browser localhost/update/update.php? value = A Results show "A" But the problem when I send from Android and try to show the results it gives an exception and shows a message :PostActivity: error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

 // ph file : 
    <?php

  if(!isset($_GET['value']))
echo json_encode("a");
else 
echo json_encode('0');

    ?>


    // MainActivity


    public class MainActivity extends AppCompatActivity{
        private APIServicePost mService;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mService = ApiUtils.getSOService();
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   sendPost("yes");
                }
            }, 1000);
        }
        public void sendPost(String title) {
            mService.savePost(title).enqueue(new Callback<Post>(){
                @Override
                public void onResponse(Call<Post> call, Response<Post> response){
                    if(response.isSuccessful()) {
                        Log.i("PostActivity", "post submitted to API." + response.body().toString());
                    }
                }
                @Override
                public void onFailure(Call<Post> call, Throwable t) {
                    Log.e("PostActivity", "error: "+t.toString());
                }
            });
        }
        // End .....
    }


    // class ApiUtils 

    public class ApiUtils {
        public static final String BASE_URL = "http://192.168.1.3/update/";
        public static APIServicePost getSOService() {
            return RetrofitClient.getClient(BASE_URL).create(APIServicePost.class);
        }
    }


    // class Post :
    public class Post {

        @SerializedName("value")
        @Expose
        private String value;
        public void setValue(String value) {
            this.value = value;
        }
        public String getValue() {
            return value;
        }
        @Override
        public String toString(){
            return "Post{" +
                    "title='" + value + '\'';
        }
    }

    // interface APIServicePost

    public interface APIServicePost {
        @POST("update.php")
        @Headers("Content-type: application/json")
        @FormUrlEncoded
        Call<Post>savePost(@Field("value") String value);
    }

    // class RetrofitClient

    public class RetrofitClient{

        private static Retrofit retrofit = null;

        public static Retrofit getClient(String baseUrl) {

            OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    Request.Builder builder = originalRequest.newBuilder().header("Authorization", Credentials.basic("aUsername", "aPassword"));
                    Request newRequest = builder.build();
                    return chain.proceed(newRequest);
                }
            }).build();

            if (retrofit==null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .addConverterFactory(new NullOnEmptyConverterFactory())
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                         .client(okHttpClient)
                        .build();
            }
            return retrofit;
        }
    }


    // class  NullOnEmptyConverterFactory

    public class NullOnEmptyConverterFactory extends Converter.Factory {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
            return new Converter<ResponseBody, Object>() {
                @Override
                public Object convert(ResponseBody body) throws IOException {
                    if (body.contentLength() == 0) return null;
                    return delegate.convert(body);
                }
            };
        }
    }

Paste this at the end of your php where you are returning response

          $set['Response'] = myResponse;
          header( 'Content-Type: application/json; charset=utf-8' );
          echo $val= str_replace('\\/', '/', json_encode($set,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
          die();

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