Retrofit and POST
Working on learning how to create a HTTP POST request using the Retrofit library in my latest Android app. Retrofit is also on a list of libraries that are "must learn" when it comes to Android. It does seem to make things easier, but I could use some more concrete examples.
There are plenty of examples with people using GET requests and then doing fun things with the resulting HTML, but there doesn't seem to be a lot of information on using POST.
After a couple of hours playing around with a test class in IntelliJ I think I have things largely figured out.
public class Main {
public static final String API_URL = "http://127.0.0.1:5000";
private static class Barcode {
final String barcode;
Barcode(String barcode) {
this.barcode = barcode;
}
}
private static class BarcodeData {
final String status;
final String created_at;
BarcodeData() {
this.status = "";
this.created_at = "";
}
}
interface PostTo {
@POST("/")
void sendBarcode(@Body Barcode body, Callback<BarcodeData> callBack);
}
public static void main(String... args) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
String talle = "043396158689";
PostTo post = restAdapter.create(PostTo.class);
post.sendBarcode(new Barcode(talle), new Callback<BarcodeData>() {
@Override
public void success(BarcodeData barcodeData, Response response) {
System.out.println("barcode: " + barcodeData.created_at);
}
@Override
public void failure(RetrofitError retrofitError) {
System.out.println(retrofitError.getMessage());
}
});
}
}
The plan is to use a barcode scanner to send the data to a server as you can probably tell.
My confusion points are what type of objects to use for the JSON returned by the server, and how to get things setup for asynchronous callback methods. I think I've figured out most of it.
I'm able to send a POST to my Flask server anyway.
Party On!