Android Application Development Cookbook by Wei-Meng Lee

Android Application Development Cookbook by Wei-Meng Lee

Author:Wei-Meng Lee
Language: eng
Format: epub
Publisher: John Wiley & Sons, Inc.
Published: 2012-12-17T16:00:00+00:00


In the OpenHttpPOSTConnection() method, you make use of the HttpPost class to add headers that you need to send to the server. In particular, you need to set the HOST and Content-Type headers. You also need to send the currency information using the setEntity() method of the HttpPost object. Here, the data (FromCurrency and ToCurrency) is passed in as a list of NameValuePair objects.

As in the previous recipe, you call the OpenHttpPOSTConnection() method in the DownloadText() method so that it can download the returned result:

private String DownloadText(String URL) { int BUFFER_SIZE = 2000; InputStream in = null; try { in = OpenHttpPOSTConnection(URL); } catch (Exception e) { Log.d("Networking", e.getLocalizedMessage()); return ""; } InputStreamReader isr = new InputStreamReader(in); int charRead; String str = ""; char[] inputBuffer = new char[BUFFER_SIZE]; try { while ((charRead = isr.read(inputBuffer)) > 0) { // ---convert the chars to a String--- String readString = String .copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new char[BUFFER_SIZE]; } in.close(); } catch (IOException e) { Log.d("DownloadText", e.getLocalizedMessage()); return ""; } return str; }

You also need to call the DownloadText() method in a separate thread, so wrap it using a subclass of the AsyncTask class:

private class DownloadTextTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls) { return DownloadText(urls[0]); } @Override protected void onPostExecute(String result) { Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); Log.d("DownloadTextTask", result); } }

Finally, call the web service using the DownloadTextTask class using the following statement:

//---using HTTP POST--- new DownloadTextTask().execute("http://www.webservicex.net/ CurrencyConvertor.asmx/ConversionRate");

NOTE Remember that you need to have the INTERNET permission in the AndroidManifest.xml file.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.