通过改造发送字符串到服务器 - Android?

时间:2017-04-10 10:32:46

标签: android retrofit retrofit2

我将string通过retrofit传递给server,如下所示:

private static final String TEST_QUERY = "query{echo(message:\"Hello\")}";

但是当我从服务器获取日志时,我得到的字符串如下:

"query{echo(message:\"Hello\")}"

但是我需要像下面那样得到它:

query{echo(message:"Hello")}

贝娄是我的代码:

public class MainActivity extends AppCompatActivity {
    private API mApi;
    private static final String TEST_QUERY = "query{echo(message:\"Hello\")}";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createApi();
        mApi = createApi();
        callMe();
    }

    private void callMe() {
        Call<CustomMutation> accountCall = mApi.queryWithCall(TEST_QUERY);
        accountCall.enqueue(new Callback<CustomMutation>() {
            @Override
            public void onResponse(Call<CustomMutation> call, Response<CustomMutation> response) {
                if (response.isSuccessful()) {
                    //DataMutation account = response.body();
                    Log.i("AAAAAAAA", "A" + response.body().getData().getEcho() + "");
                } else {
                    Log.i("AAAAAAAA", "B");
                }
            }

            @Override
            public void onFailure(Call<CustomMutation> call, Throwable t) {
                Log.i("AAAAAAAA", "C  " + t.getMessage());
            }
        });
        Log.i("AAAAAAAA", accountCall.request().url() + "");
    }

    private API createApi() {
        OkHttpClient ok = new OkHttpClient.Builder()
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://88.99.132.161/")
                .client(ok)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(API.class);
    }
}

我的Interface

interface API {
    @POST("graphql/server.php")
    Call<CustomMutation> queryWithCall(@Body String query);
}

我的图书馆是:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'

1 个答案:

答案 0 :(得分:0)

您应该尝试使用Scalars Converter:

将此添加到您的build.gradle

compile  'com.squareup.retrofit2:converter-scalars:2.1.0'  

您的createApi()应该是这样的:

private API createApi() {
    OkHttpClient ok = new OkHttpClient.Builder()
            .build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://88.99.132.161/")
            .client(ok)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    return retrofit.create(API.class);
}