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!!!!!!~