简体   繁体   中英

Android, Retrofit 2 POST request

I'm new to Android developing and I don't know how to do this, I've searched on the internet, but everything I've tried so far doesn't work. What I'm trying to do, is to send string to the server and the key must be "interval=". This is what I have so far, but it doesn't work. I'm getting string time2 from spinner, but for now it doesn't matter, because I know that the spinner part works and POST doesn't.

 PostInterface service = retrofit.create(PostInterface.class);
    service.postTime(time2);

and interface

@FormUrlEncoded
@POST
Call<Response> postTime(@Field("interval=") String time);

What I'm supposed to do net and how can I test it with http://requestb.in/ (never used it before, I just saw it can be used for POST testing)?

Why do you use retrofit in the first place ? It's a good library, but if you're new to Android, i suggest to start with HttpClient.

In your sample, the execute method was not called.

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://requestb.in/")
.addConverterFactory(GsonConverterFactory.create())
.build();
PostInterface service = retrofit.create(PostInterface.class);
Call<Response> call = service.postTime(time2);
call.execute()

In your interface (replace xxx by the token given by requestbin)

@FormUrlEncoded
@POST("xxxxxxx")
Call<Response> postTime(@Field("interval=") String time);

ps: Be aware that you should not launch any http calls on the main thread.

if you are posting a form field, you should remove the "=" from "interval=" fields are key and values, no need for the "=" if you want a test client for posts and get you can try postman

please clarify your question more if this is not what you expected as an answer


as @Mickael Monsang Answer dont' use call.execute directly better use

call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<Response> call, Response<Response> response) {}}
        @Override
        public void onFailure(Call<String> call, Throwable t) {

            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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