1

I followed this article to build my own RESTful API server before. Now, I would like to send a POST request to my API server in android studio. I followed this reply, but it is not successful.

Here is part of my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_events_create);

    ActionBar actionBar = this.getSupportActionBar();
    actionBar.setTitle("Test");
    actionBar.setDisplayHomeAsUpEnabled(true);


    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL("http://myip/task_manager/v1/register");
        connection = (HttpURLConnection)url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
        connection.connect();

        //Send request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream ());
        wr.writeBytes("Parameter String"); // I dunno how to write this string..
        wr.flush();
        wr.close ();

        InputStream is;
        int response = connection.getResponseCode();
        if (response >= 200 && response <=399){
            //return is = connection.getInputStream();
            //return true;
        } else {
            //return is = connection.getErrorStream();
            //return false;
        }


    } catch (Exception e) {

        e.printStackTrace();
        //return false;

    } finally {

        if(connection != null) {
            connection.disconnect();
        }
    }

}

Here is my questions:
1. When "connection.connect();" is run, there is error in console. Is my url string is wrong?
2. What should the "Parameter String" be like? (my parameters are email=xxx, name=yyy)
3. Is there any better method to send a POST request?

Thanks a lot!!!!!!~

Chan Chris
  • 13
  • 1
  • 1
  • 3

2 Answers2

3

to answer your question #3 would suggest using a library like OkHTTP to make that post request. That will make your code way simpler and easier to debug.

Make sure you have the following permissions on your Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Add the library to your gradle file:

compile 'com.squareup.okhttp3:okhttp:3.10.0'

Then, change your onCreate method to the following:

private final OkHttpClient client = new OkHttpClient();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_events_create);

    ActionBar actionBar = this.getSupportActionBar();
    actionBar.setTitle("Test");
    actionBar.setDisplayHomeAsUpEnabled(true);

    makePost();
}

private void makePost(){
    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("email", "your-email@email.com")
        .addFormDataPart("name", "your-name")
        .build();

    request = new Request.Builder()
        .url("http://myip/task_manager/v1/register")
        .post(requestBody)
        .build();

    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      Headers responseHeaders = response.headers();
      for (int i = 0; i < responseHeaders.size(); i++) {
        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
      }

      System.out.println(response.body().string());
   }
}

And this should make a post request to your endpoint.

If you wanna log it, you can just add a logging interceptor to it.

Hope this helps you out!

Marcos Placona
  • 21,468
  • 11
  • 68
  • 93
  • How to execute the request? I googled for it and the answer is "Response response = client.newCall(request).execute();", but i dunno where to declare the variable client. Thx~ – Chan Chris Mar 12 '18 at 12:10
  • Updated the code with exactly what you should need. Have a look at some of the recipes in the docs for more information: https://github.com/square/okhttp/wiki/Recipes – Marcos Placona Mar 12 '18 at 14:34
  • I think it should be "Request request" – gaming_enthusiast Nov 27 '18 at 05:27
1

Please use volley or retrofit dependency for api calls in android as it is easy to use

Volley Tutorial: https://www.androidtutorialpoint.com/networking/android-volley-tutorial/

Retrofit Tutorial: https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

Please refer these two

Nibin Salim
  • 71
  • 1
  • 7