繁体   English   中英

就像在jQuery ajax中一样,使用Retrofit发出POST Json请求

[英]Make a POST Json request using Retrofit just like in jQuery ajax

我正在使用我网站上的jQuery ajax向我们的服务器发出POST请求,因此它可以向我发送我可以使用的json数据。 我正在执行的所有ajax请求都如下所示:

getLanguages(callback) {
    $.ajax({
        type: 'POST',
        crossDomain: true,
        dataType: 'JSON',
        cache: false,
        url: 'https://www.someurl.com/fc.php',
        data: {
            mode: 'language'
        },
        success: callback
    });
},

requestCountries(phone, callback) {
    $.ajax({
        type: 'POST',
        crossDomain: true,
        dataType: 'JSON',
        cache: false,
        url: 'https://www.someurl.com/fc.php',
        data: {
            mode: 'country',
            phone: phone,
            langId: myStorage.getLanguage()
        },
        success: callback
    });
},

唯一不同的是data参数,所以这很重要。 现在,我正在尝试使用Retrofit在Android中实现相同的功能,但是我什么都不明白,因为它基本上没有文档,因此,这是我从这里到那里的用户示例构建的内容:

    String url = "https://www.someurl.com";
    JsonObject obj = new JsonObject();
    obj.addProperty("mode", "language");
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    MyRetrofit myretro = retrofit.create(MyRetrofit.class);
    myretro.getLanguage(obj, new Callback<Language>() {

        @Override
        public void onResponse(Call<Language> call, Response<Language> response) {
            Log.d("response", "response");
        }

        @Override
        public void onFailure(Call<Language> call, Throwable t) {
            Log.d("response", "response");
        }
    });

这是MyRetrofit.java

public interface MyRetrofit {

    @POST("/fc.php")
    Call<Void> getLanguage(@Body JsonObject json, Callback<Language> callback);
}

这是语言课

public class Language {
    private String langId;
    private String langName;
    private String langIcon;
}

当我运行代码时,它因该错误而崩溃

java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #2)

我如何才能实现我所需要的,任何帮助,解释或建议都值得赞赏。

你可以试试

 // you do not need callback parameter here
 public interface MyRetrofit {

@POST("fc.php")
Call<Language> getLanguage(@Body JsonObject json);
  } 

还要确保您的baseurl是

https://www.someurl.com/

终点是fc.php

  @POST("fc.php") 

例如,假设您将端点作为post / user,那么您将拥有@POST(“ post / user”),而您的baseurl将是https://www.someurl.com/ 还可以将一些实用程序文件作为常量放置在baseurl中,并定义端点,以便您可以轻松地在一个地方更改它们并在需要的地方引用它。

然后

Call<Language> call = myretro.getLanguage(obj);
// for asynchronous call
call.enqueue(new Callback<Language>() {

    @Override
    public void onResponse(Call<Language> call, Response<Language> response) {
        Log.d("response", "response");
    }

    @Override
    public void onFailure(Call<Language> call, Throwable t) {
        t.printstackTrace();

    }
});

提示:您可以使用pojo并使用gsonconverter获得的gson将它们转换为json。

编辑:对于调试,您可以记录请求和响应

   OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {

            Request originalRequest = chain.request(); //Current Request

            Response response = chain.proceed(originalRequest); //Get response of the request

            //I am logging the response body in debug mode. When I do this I consume the response (OKHttp only lets you do this once) so i have re-build a new one using the cached body
            String bodyString = response.body().string();

            Log.i("NetworkModule", String.format("Sending request %s with headers %s ", originalRequest.url(), originalRequest.headers()));
            Log.i("", (String.format("Got response HTTP %s %s \n\n with body %s \n\n with headers %s ", response.code(), response.message(), bodyString, response.headers())));

            response = response.newBuilder().body(
                    ResponseBody.create(response.body().contentType(), bodyString))
                    .build();

            return response;
        }
    }).connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(1, TimeUnit.MINUTES).writeTimeout(2, TimeUnit.MINUTES).build();

然后

   Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))          
            .build();

尝试

Call<Void> getUser(....)

暂无
暂无

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

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