LoginSignup
29
24

More than 5 years have passed since last update.

RetrofitでJSONをPOSTする

Last updated at Posted at 2016-05-31

Server

#sinatra

post '/user', provides: :json do
  params = JSON.parse request.body.read
  puts params['name']
  puts params['age']
end

Curl

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"hogehoge","age":"30"}' http://localhost:9292/user -w "\n%{http_code}\n"

Java

#Retrofit

public interface ApiService {
    @Headers({
        "Accept: application/json",
        "Content-type: application/json"
    })
    @POST("/user")
    Observable<Void> createUser(@Body HashMap<String, String> body);
}

おまけ

#実装詳細


// post
public static Observable<Void> postUser(String name, int age) {
    // create Retrofit
    Retrofit retrofit = new Retrofit.Builder()
        .client(new OkHttpClient.Builder().build())
        .baseUrl("http://localhost:9292")
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    return retrofit.createUser(createUserBody(name, age));
}

// create params
private static HashMap<String, String> createUserBody(String name, int age) {
    HashMap<String, String> hashMap = new HashMap<>();
    hashMap.put("name", name);
    hashMap.put("age", String.valueOf(age));
    return hashMap;
}

// API
public interface ApiService {
    @Headers({
        "Accept: application/json",
        "Content-type: application/json"
    })
    @POST("/user")
    Observable<Void> createUser(@Body HashMap<String, String> body);
}

29
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
24