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

标签 java android jquery ajax retrofit2

我在我的网站上使用 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 并使用 gson 将它们转换为 json,这是您通过 gsonconverter 获得的。

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

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

关于java - 像在 jQuery ajax 中一样使用 Retrofit 发出 POST Json 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44722421/

相关文章:

安卓自定义按钮;改变文字颜色

android - 获取弹出窗口内 View 的绝对坐标

javascript - HighCharts Semi-Circle-Donut,去除边距和填充

javascript - jQuery 返回样式属性的简写 CSS

java - DoFn.Setup 和 DoFn.StartBundle 有什么区别?

android - 无法在我的代码中激活我的自定义权限

java - 使用 JAVA 项目或 AEM 实现 Akamai CCU V3 快速清除

javascript - 将任何出现的对象名称替换为对象值

java - Sqlite 列确定错误

java - 非黑色背景的吴氏抗锯齿线算法