无法发送值和改造后的响应2

时间:2019-01-26 04:51:59

标签: java android retrofit2

我有一个PHP文件,可以从Android接收数据,当我从浏览器localhost / update / update.php测试PHP文件时?值= A 结果显示为“ A”,但是当我从Android发送并尝试显示结果时出现问题,它给出异常并显示消息:PostActivity:错误:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但之前为第1行第2列的路径$

 // 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);
                }
            };
        }
    }

1 个答案:

答案 0 :(得分:0)

将此内容粘贴到您的php末尾,您将在其中返回响应

          $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();