相关疑难解决方法(0)

POST主体JSON使用Retrofit

我正在尝试使用Retrofit库POST一个JSONObject,但是当我在接收端看到请求时,内容长度为0.

在RestService接口中:

@Headers({
        "Content-type: application/json"
})
@POST("/api/v1/user/controller")
void registerController( 
     @Body JSONObject registrationBundle, 
     @Header("x-company-device-token") String companyDeviceToken, 
     @Header("x-company-device-guid") String companyDeviceGuid, 
     Callback<JSONObject> cb);
Run Code Online (Sandbox Code Playgroud)

它被调用,

mRestService.registerController(
    registrationBundle, 
    mApplication.mSession.getCredentials().getDeviceToken(), 
    mApplication.mSession.getCredentials().getDeviceGuid(),
    new Callback<JSONObject>() {
        // ...
    }
)
Run Code Online (Sandbox Code Playgroud)

我确定registrationBundle,这是一个JSONObject非空或空(其他字段肯定是好的).在提出请求时,它将注销为: {"zip":19312,"useAccountZip":false,"controllerName":"mine","registrationCode":"GLD94Q"}.

在请求的接收端,我看到请求已经Content-type: application/json有了Content-length: 0.

是否有任何理由为什么在这样的身体中发送JSON不起作用?我在使用Retrofit时遗漏了一些简单的东西吗?

rest post android json retrofit

10
推荐指数
1
解决办法
3万
查看次数

@Part参数只能与多部分编码一起使用.(参数#8)

在我在这里发布这个问题之前,我已经尝试添加@Multipart上面的接口方法并且在stackoverflow中搜索仍然找不到类似我的问题.

在这种情况下,我尝试使用TypedFile服务器发送图像.我的界面方法如下所示:

 @Headers({"Content-type: application/json"})
    @POST("/user/change")
    void postChange(@Query("name") String name, @Query("email") String  email, @Query("password") String password, @Query("phone") String phone, @Query("user_id") String userId, @Query("address[]") String[] listAddress, @Query("head[]") String[] head, @Part("photo_profile") TypedFile photoProfile, @Body TypedInput jsonObject, Callback<ReceiveDTO> callback);
Run Code Online (Sandbox Code Playgroud)

编辑

在那种方法中,我们可以看到@Part@Body.如果我添加@Multipart上面的方法,我们将抛出一个错误@Body parameters cannot be used with form or multi-part encoding. (parameter #9)

我正在使用Retrofit 1.9

android multipartentity retrofit

10
推荐指数
2
解决办法
1万
查看次数

如何在Android上使用GraphQL和Retrofit?

我是GraphQL的新手,但我现在已经使用Retrofit一段时间了,它易于使用且速度快.就传递数据的方式而言,GraphQL与rest apis有很大不同.关于在Android上使用GraphQL,确实没有太多的教程,我只能找到这个视频(https://www.youtube.com/watch?v=P0uJHI7GjIc&t=1s),但那里没有真正的代码.

在我当前的改装调用代码中,我有一个端点,我设置如下:

final RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .build();
        T service = restAdapter.create(clazz);
Run Code Online (Sandbox Code Playgroud)

然后我打电话给这样的休息服务:

@GET("/users/{login}")
    Observable<Github> getUser(@Path("login") String login);
Run Code Online (Sandbox Code Playgroud)

现在使用GraphQL,您只有一个基本URL,没有服务路径.此外,如果您查询userId = 1,则必须发送为带有Body参数的Post:

operationName: arbitrary name ,
query: "{users(userid:$userId){username}}, 
variables: "{"userId":1}"
Run Code Online (Sandbox Code Playgroud)

我只是不确定这是如何转化为Retrofit的

android retrofit graphql

7
推荐指数
2
解决办法
6614
查看次数

改造@Body在HTTP请求中显示为参数

我之前已成功使用Square的Retrofit进行@GETWeb API调用,但是当尝试@BODY@POST调用中发送JSON时,在服务器(Rails)上,JSON显示为参数而不是正文请求.

我的理解是将该@BODY方法参数添加到正文中的请求中.

知道我做错了什么吗?

WebApi:

@POST("/api/v1/gear/scans.json")
Response postScans(
    @Header(HEADER_AUTH) String token,
    @Body JsonObject scans
);
Run Code Online (Sandbox Code Playgroud)

提出网络请求:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(api_url)
    .build();
WebApi webApi = restAdapter.create(AssetsWebApi.class);     
Response response = webApi.postScans(auth_token, valid_json);
Run Code Online (Sandbox Code Playgroud)

android ruby-on-rails http-post retrofit

5
推荐指数
1
解决办法
8509
查看次数

如何使用 Retrofit 发布数组参数?

我想post数据如下:

   {
     "user_id":"14545646",
    "list":["4545645","4545645","4545645","4545645"]
   }
Run Code Online (Sandbox Code Playgroud)

我使用了以下Retrofit方法:

interface DeleteOrder {

         @FormUrlEncoded
         @POST("/api/shop/deleteOrder.json")
         void getPoJoDeleteOrder(@Field("user_id") String user_id, @Field("list") String[] list,Callback<PoJoDeleteOrder> callback);

      }
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

retrofit

5
推荐指数
1
解决办法
9672
查看次数

如何使用 Retrofit 在 JSON 请求中获取“nameValuePairs”?

我如何发布JSONObject像下面这样的请求?

原始请求:

    {
        "pObj": [],
        "robj": [
            {
                "l_index": "1",
                "user_id": "111",
                "vername": "1",
                "fcmtoken": "ghkghkhkh"
            }
        ],
        "uobject": [],
        "pname": "y6y68uuy7"
    }
Run Code Online (Sandbox Code Playgroud)

在 Volley 中,我可以成功发布JSONObject请求。但是当我在 Retrofit 中使用它时,我的请求更改如下:

我在日志中得到了什么:

  {
        "nameValuePairs": {
            "pObj": {
                "values": []
            },
            "robj": {
                "values": [
                    {
                        "nameValuePairs": {
                            "l_index": "1",
                            "user_id": "111",
                            "vername": "1",
                            "fcmtoken": "ghkghkhkh"
                        }
                    }
                ]
            },
            "uobject": {
                "values": []
            },
                    "pname": "y6y68uuy7"
        }
    }
Run Code Online (Sandbox Code Playgroud)

我收到了来自服务器端的错误请求。

我的改造 API 接口:

public interface ApiInterface {

    @Headers( "Content-Type: application/json; …
Run Code Online (Sandbox Code Playgroud)

android json retrofit2

5
推荐指数
1
解决办法
2070
查看次数

Retrofit2 POST 主体作为原始 JSON

我正在尝试使用Microsoft 翻译器 API翻译一些文本。我正在使用Retrofit 2. 这是代码:

 public RestClient() {
    final OkHttpClient httpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    final Request originalRequest = chain.request();
                    Request newRequest;

                    newRequest = originalRequest.newBuilder()
                            .header("Content-Type", "application/json")
                            .header("Ocp-Apim-Subscription-Key", "KEY")
                            .header("X-ClientTraceId", java.util.UUID.randomUUID().toString())
                            .build();
                    return chain.proceed(newRequest);
                }
            })
            .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();


    // Build the retrofit config from our http client
    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.cognitive.microsofttranslator.com/")
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Build api instance from retrofit config
    api …
Run Code Online (Sandbox Code Playgroud)

post android request retrofit2

5
推荐指数
1
解决办法
6796
查看次数

如何在使用 Retrofit + Moshi 时为 json 键指定不同的名称

我需要使用以下 json 向后端发出 POST 请求:

{
    start_time: 123456789
}
Run Code Online (Sandbox Code Playgroud)

我在 Retrofit 请求中为主体创建了以下数据类:

{
    start_time: 123456789
}
Run Code Online (Sandbox Code Playgroud)

但是当我检查后端时,请求包含该startTime字段而不是start_time. 如何更改此变量的名称以进行 json 序列化?

编辑:我的build.gradle:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
Run Code Online (Sandbox Code Playgroud)

我的api接口:

data class MyRequestBody(
    @Json(name="start_time")
    val startTime: Long
)
Run Code Online (Sandbox Code Playgroud)

改造建造者:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
Run Code Online (Sandbox Code Playgroud)

android json kotlin moshi retrofit2

5
推荐指数
1
解决办法
1353
查看次数

改造:出现错误 ** 第 1 行第 1 列输入结束**

我不知道我的问题出在哪里。我必须发布原始的身体

{"app_id":"abced","app_key":"abced","request":"login","username":"abce@gmail.com","password":"1234"}
Run Code Online (Sandbox Code Playgroud)

我正在使用改造 2.0。我创建了一个界面

    @FormUrlEncoded
@POST("index.php/")
Call<LoginResponse> getHome(@Field("app_id") String request,
                            @Field("app_key") String request1,
                            @Field("request") String request2,
                            @Field("username") String request3,
                            @Field("password") String request4);
Run Code Online (Sandbox Code Playgroud)

并像这样调用:

 Retrofit retrofitget = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        MyAPI ApiData = retrofitget.create(MyAPI.class);
        Call<LoginResponse> GalleryGetSet = ApiData.getHome("abced","abced","login","abce@gmail.com","1234");
        GalleryGetSet.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                Log.e(TAG, "data1" + response.body().getError());
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                Log.e(TAG, "Error2" + t.getMessage());
            }
        });
Run Code Online (Sandbox Code Playgroud)

总是出错:第 1 行第 1 列的输入结束 通过改装帖子发布原始身体数据的过程是否正确,或者我错了。已经谷歌它但没有得到我的解决方案。请任何人帮助我。

在界面上也是这样试的

@FormUrlEncoded …
Run Code Online (Sandbox Code Playgroud)

post android retrofit retrofit2

4
推荐指数
1
解决办法
1万
查看次数

如何在改造中使用HashMap发布数据?

能否请您解释了如何使用发布数据的HashMapretrofit2

post android get gson retrofit2

4
推荐指数
1
解决办法
6405
查看次数

使用改造的邮政请求正文中的原始字符串

我想在post请求体中发送user:user .我正在使用改造 lib.请建议我.

我已经尝试过这样了

@POST(/login)
void login(@BODY String s,Callback<LoginResponse>)
Run Code Online (Sandbox Code Playgroud)

并称之为

login("user:user",Callback<LoginResponse>)

java retrofit

3
推荐指数
1
解决办法
5168
查看次数

使用body的改进2.0 POST方法是String

之前可能已经提出过这个问题,但是对于新版本2.0,我还没有找到任何正确的答案.

我的问题如下:

public interface  AuthenticationAPI {

    @POST("token")
    Call<String> authenticate(@Body String  body);

}
Run Code Online (Sandbox Code Playgroud)

然后我打电话给:

Retrofit retrofit = new Retrofit.Builder().baseUrl(authenUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AuthenticationAPI authen = retrofit.create(AuthenticationAPI.class);


        try {
            Call<String> call1 = authen.authenticate(authenBody);
            call1.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Response<String> response, Retrofit retrofit) {
                    Log.d("THAIPD", "Success " + response.raw().message());
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e("THAIPD", " FAIL " + t.getMessage());
                }
            });
        } catch (Exception e) {
            Log.e("THAIPD", e.getMessage());
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

然后我收到响应protocol=http/1.1, code=400, message=Bad Request,这意味着我的身体参数不正确.

当我尝试使用其他工具作为Postman提出请求时,我得到了正确的结果,代码是200.

我找到了这个答案,但 …

android retrofit

3
推荐指数
1
解决办法
7925
查看次数

如何在 Android 中使用 Retrofit 发送 JSON POST 请求,并接收字符串响应

我是第一次使用 Retrofit2,遇到了一些问题。

这是用于调用 REST API 的代码片段

    //building retrofit object
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.0.71:9000/api/uniapp/")
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .build();

    APIService service = retrofit.create(APIService.class);

    //defining the call
    Call<String> call = service.refreshAppMetaConfig("0");
    //calling the api
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            //displaying the message from the response as toast
            System.out.println("Uniapp :"+response);
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            System.out.println("Uniapp :"+t.getMessage());
        }
    });
Run Code Online (Sandbox Code Playgroud)

这是 APIService 类:

public interface APIService {

    //The register call
    @FormUrlEncoded
    @POST("appmetaconfigjson")
    Call<String> refreshAppMetaConfig(@Field("versionId") …
Run Code Online (Sandbox Code Playgroud)

post android json playframework retrofit2

3
推荐指数
1
解决办法
6299
查看次数