简体   繁体   English

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

[英]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? 我有一个PHP文件,可从Android接收数据,当我从浏览器localhost / update / update.php测试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 $ 值= A结果显示为“ A”,但是当我从Android发送并尝试显示结果时出现问题,它给出了异常并显示了一条消息:PostActivity:错误:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期BEGIN_OBJECT,但位于第1行第2列路径$ STRING

 // 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 将其粘贴到您的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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM