Skip to content

Instantly share code, notes, and snippets.

@matthew-carroll
Last active August 29, 2015 13:59
Show Gist options
  • Save matthew-carroll/10441104 to your computer and use it in GitHub Desktop.
Save matthew-carroll/10441104 to your computer and use it in GitHub Desktop.
Intro to Retrofit by Square
// Compose a single request to send to the server:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.myserver.com/apis/users/" + userId + "/profile");
List<NameValuePair> bodyParams = new ArrayList<NameValuePair>();
pairs.add(new NameValuePair("first_name", firstName));
pairs.add(new NameValuePair("last_name", firstName));
pairs.add(new NameValuePair("street1", firstName));
pairs.add(new NameValuePair("street2", firstName));
pairs.add(new NameValuePair("zip", firstName));
// as many key/values as you can stand to type...
post.setEntity(new UrlEncodedFormEntity(pairs));
// Send request and receive response
HttpResponse response = client.execute(post);
// Now remind yourself this is all just for one single request to your server
// - go checkout Retrofit by Square
// Stub out all of your service endpoints in an Interface
public interface MyWebserviceApi
{
// The following method stub sets up a server call that will be POSTed
// to the server, it will be sent to the "apis/users/{id}/proflie"
// resource, and any included fields will be form URL encoded.
@FormUrlEncoded
@POST("/apis/users/{id}/profile")
Response editProfile(@Path("id") String userId,
@Field("first_name") String firstName, @Field("last_name") String lastName,
@Field("street1") String street1, @Field("street2") String street2, @field("zip") String zip);
// add as many other endpoints as you wish - they can be
// GET, POST, DELETE
}
// The creation of MyWebserviceApi below need only be done one time as long
// as you hold a global reference to it - no need to repeat it each time you
// make a call.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.myserver.com")
.build();
MyWebserviceApi webservice = restAdapter.create(RetrofitApi.java);
// Send request to server
// are you ready? get set. GO!
Response response = webservice.editProfile(userId, firstName, lastName, street1, street2, zip);
// yep, that ^ was it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment