Skip to content

Instantly share code, notes, and snippets.

@shts
Last active June 1, 2016 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shts/27246262b014992e39174de360d20df9 to your computer and use it in GitHub Desktop.
Save shts/27246262b014992e39174de360d20df9 to your computer and use it in GitHub Desktop.
RetrofitでJSONをPOSTする ref: http://qiita.com/shts/items/775973783966ce7b19cf
post '/user', provides: :json do
params = JSON.parse request.body.read
puts params['name']
puts params['age']
end
$ 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"
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment