Android - POST for RESTful web service

I am looking for some recommendations on how to send data to a web service in an Android app. Unfortunately, this is a school project, so I can not use external libraries.

The web service has a base URL, for example:

http://example.com/service/create 

And it takes two variables in the following format:

 username = "user1" locationname = "location1" 

The web service is RESTful and uses an XML structure, if that matters. From my research, I understand that I should use a URL connection and not an outdated HTTP connection, but I can not find an example of what I'm looking for.

Here is my attempt, which is currently not working:

 import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toPost test = new toPost(); text.execute(); } private class toPost extends AsyncTask<URL, Void, String> { @Override protected String doInBackground(URL... params) { HttpURLConnection conn = null; try { URL url = new URL("http://example.com/service"); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String body = "username=user1&locationname=location1"; OutputStream output = new BufferedOutputStream(conn.getOutputStream()); output.write(body.getBytes()); output.flush(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { conn.disconnect(); } return null; } } } 
+5
source share
8 answers

I would use the volley library as suggested by Google .

The execution of the request is explained on this page, but as simple as:

 final TextView mTextView = (TextView) findViewById(R.id.text); ... // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(this); String url ="http://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. mTextView.setText("Response is: "+ response.substring(0,500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTextView.setText("That didn't work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest); 
+2
source

If you want to use the HttpUrlConnection, you can refer to the following two samples. Hope this helps!

 private class LoginRequest extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { String address = "http://server/login"; HttpURLConnection urlConnection; String requestBody; Uri.Builder builder = new Uri.Builder(); Map<String, String> params = new HashMap<>(); params.put("username", "bnk"); params.put("password", "bnk123"); // encode parameters Iterator entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString()); entries.remove(); } requestBody = builder.build().getEncodedQuery(); try { URL url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); JSONObject jsonObject = new JSONObject(); InputStream inputStream; // get stream if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } // parse stream BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String temp, response = ""; while ((temp = bufferedReader.readLine()) != null) { response += temp; } // put into JSONObject jsonObject.put("Content", response); jsonObject.put("Message", urlConnection.getResponseMessage()); jsonObject.put("Length", urlConnection.getContentLength()); jsonObject.put("Type", urlConnection.getContentType()); return jsonObject.toString(); } catch (IOException | JSONException e) { return e.toString(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.i(LOG_TAG, "POST\n" + result); } } private class JsonPostRequest extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { try { String address = "http://server/postvalue"; JSONObject json = new JSONObject(); json.put("Title", "Dummy Title"); json.put("Author", "Dummy Author"); String requestBody = json.toString(); URL url = new URL(address); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); InputStream inputStream; // get stream if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } // parse stream BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String temp, response = ""; while ((temp = bufferedReader.readLine()) != null) { response += temp; } // put into JSONObject JSONObject jsonObject = new JSONObject(); jsonObject.put("Content", response); jsonObject.put("Message", urlConnection.getResponseMessage()); jsonObject.put("Length", urlConnection.getContentLength()); jsonObject.put("Type", urlConnection.getContentType()); return jsonObject.toString(); } catch (IOException | JSONException e) { return e.toString(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.i(LOG_TAG, "POST RESPONSE: " + result); mTextView.setText(result); } } 
+2
source

Yes, you must use URLConnection to execute queries.

You can send XML data as a payload.

Please Refer Android - Using HttpURLConnection to POST XML Data

  URL url = new URL(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String body = "<xml...</xml>"; OutputStream output = new BufferedOutputStream(conn.getOutputStream()); output.write(body.getBytes()); output.flush(); } finally { conn.disconnect(); } 
+1
source

My suggestion is to use Retrofit among Jackson Converter .

Retrofit supports both asynchronous and synchronous requests. It supports the GET , POST , PUT , DELETE and HEAD methods.

Jackson helps you parse the XML into a JSON object.

Both of them are very easy to use and have good documentation.

Here you can find a simple tutorial on using Retrofit.

+1
source

Use the code below to call the web rest service from the Android app. This is fully tested code.

 public class RestClient { static Context context; private static int responseCode; private static String response; public static String getResponse() { return response; } public static void setResponse(String response) { RestClient.response = response; } public static int getResponseCode() { return responseCode; } public static void setResponseCode(int responseCode) { RestClient.responseCode = responseCode; } public static void Execute(String requestMethod, String jsonData, String urlMethod, Context contextTemp, HashMap<String, Object> params) { try { context = contextTemp; String ip = context.getResources().getString(R.string.ip); StringBuilder urlString = new StringBuilder(ip + urlMethod); if (params != null) { for (Map.Entry<String, Object> para : params.entrySet()) { if (para.getValue() instanceof Long) { urlString.append("?" + para.getKey() + "=" +(Long)para.getValue()); } if (para.getValue() instanceof String) { urlString.append("?" + para.getKey() + "=" +String.valueOf(para.getValue())); } } } URL url = new URL(urlString.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(requestMethod); conn.setReadTimeout(10000 /*milliseconds*/); conn.setConnectTimeout(15000 /* milliseconds */); switch (requestMethod) { case "POST" : case "PUT": conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.connect(); OutputStream os = new BufferedOutputStream(conn.getOutputStream()); os.write(jsonData.getBytes()); os.flush(); responseCode = conn.getResponseCode(); break; case "GET": responseCode = conn.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); break; break; } if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuffer tempResponse = new StringBuffer(); while ((inputLine = in.readLine()) != null) { tempResponse.append(inputLine); } in.close(); response = tempResponse.toString(); System.out.println(response.toString()); } else { System.out.println("GET request not worked"); } } catch (IOException e) { e.printStackTrace(); } } } 
+1
source

You will need to complete the request. This can be done by calling getResponseCode () or getResponseMessage ()) or getInputStream () for the response to be returned and processed.

Working code for your example:

 import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toPost test = new toPost(); test.execute(); } private class toPost extends AsyncTask<URL, Void, String> { @Override protected String doInBackground(URL... params) { HttpURLConnection conn = null; try { URL url = new URL("http://example.com/service"); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String body = "username=user1&locationname=location1"; OutputStream output = new BufferedOutputStream(conn.getOutputStream()); output.write(body.getBytes()); output.flush(); //This is needed // Could alternatively use conn.getResponseMessage() or conn.getInputStream() conn.getResponseCode(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { conn.disconnect(); } return null; } } } 
0
source

try it. (msg - xml string)

  try { URL url = new URL(address); URLConnection uc = url.openConnection(); HttpURLConnection conn = (HttpURLConnection) uc; conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "text/xml"); PrintWriter pw = new PrintWriter(conn.getOutputStream()); pw.write(msg.getText()); pw.close(); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); bis.close(); } catch (Exception e) { e.printStackTrace(); } 
0
source

Here is an example of a GET and POST request

 public class HttpConn { public final static int GET = 1 ; public final static int POST = 2 ; Context ctx; SharedPreferences mem; public HttpConn(Context ctx , String memKey) { this.ctx = ctx; System.setProperty("http.keepAlive", "false"); } /** * POST Request */ public String postData(String url, String json ) throws Exception { Log.d("PostData", "Started"); String responseContent = ""; // Create a new HttpClient and Post Header HttpPost httppost = new HttpPost( url ); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 10000); HttpConnectionParams.setSoTimeout(myParams, 60000); HttpConnectionParams.setTcpNoDelay(myParams, true); httppost.setHeader("Content-type", "application/json"); HttpClient httpclient = new DefaultHttpClient(myParams); StringEntity se = new StringEntity( json, HTTP.UTF_8); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); responseContent = HttpConn.getResponseContent(entity); return responseContent; } /** * GET Request */ public String getData (String url , String queryString ) throws Exception { HttpResponse response = null; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); String fullUrl = url + queryString ; request.setURI(new URI( fullUrl )); response = client.execute(request); HttpEntity entity = response.getEntity(); String responseContent = HttpConn.getResponseContent(entity ); return responseContent ; } // get content of http responce public static String getResponseContent(HttpEntity entity) { StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader( entity.getContent()), 65728); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }catch (Error e) { e.printStackTrace() ; } return null ; } } 

call

 case HttpConn.GET: Log.i("HttpConn.GET", "url:" + url); payload = queryString(queryParams); response = httpConn.getData(url, queryString(queryParams)); break; case HttpConn.POST: Log.i("HttpConn.POST", "url:" + url); Log.i("Payload", "json:" + jsonObj.toString()); payload = jsonObj.toString(); response = httpConn.postData(url, jsonObj); break; 
-1
source

Source: https://habr.com/ru/post/1236097/


All Articles