Last active
June 1, 2016 01:27
-
-
Save shts/27246262b014992e39174de360d20df9 to your computer and use it in GitHub Desktop.
RetrofitでJSONをPOSTする ref: http://qiita.com/shts/items/775973783966ce7b19cf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
post '/user', provides: :json do | |
params = JSON.parse request.body.read | |
puts params['name'] | |
puts params['age'] | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ApiService { | |
@Headers({ | |
"Accept: application/json", | |
"Content-type: application/json" | |
}) | |
@POST("/user") | |
Observable<Void> createUser(@Body HashMap<String, String> body); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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