05-accessing_web

stuckwarmersMobile - Wireless

Dec 14, 2013 (3 years and 7 months ago)

173 views

Sabancı University, Copyri
g
ht 2009

Android

Programming

04


Accessing Internet

WebView


This class is the basis upon which you can roll your
own web browser or simply display some online
content within your Activity


It uses the WebKit rendering engine to display web
pages and includes methods to navigate forward and
backward through a history, zoom in and out, perform
text searches and more


To access internet add permission to the manifest


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


Sabancı University, Copyri
g
ht 2009

WebView


Basic Usage


Just create an ACTION_VIEW intent with a
URI object and shoot

Sabancı University, Copyri
g
ht 2009

Uri uri = Uri.parse("http://www.example.com");


Intent intent = new Intent(Intent.ACTION_VIEW, uri);


startActivity(intent);

Loading a Web Page


Invoke loadUrl() method with the url string of
the web page

Sabancı University, Copyri
g
ht 2009

@Override

public void onCreate(Bundle icicle) {

}


super.onCreate(icicle); setContentView(R.layout.main);


browser=(WebView)findViewById(R.id.webkit);


browser.loadUrl("http://commonsware.com");

}

Loading HTML


Invoke the loadData() method with the
required HTML text parameter

Sabancı University, Copyri
g
ht 2009

@Override

public void onCreate(Bundle icicle) {

}


super.onCreate(icicle); setContentView(R.layout.main);


browser=(WebView)findViewById(R.id.webkit);


browser.loadData(”<html<body>Hello, world</body></html>”,




“text/html”,”UTF
-
8”);

}

Sabancı University, Copyri
g
ht 2009

Accessing Remote Data


Preferred library is the Apache HTTPClient
library


Also java.net package is supported (uses
Apache at the background)


XMLPullParser of Xml operations


To access internet add permission to the
manifest


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

Sabancı University, Copyri
g
ht 2009

Using the HTTPClient

try {


textView.setText("");


HttpClient client = new DefaultHttpClient();


HttpGet request = new HttpGet(urlText.getText().toString());


HttpResponse response = client.execute(request);


// Get the response


BufferedReader rd = new BufferedReader(new InputStreamReader(






response.getEntity().getContent()));


String line = "";



while ((line = rd.readLine()) != null) {




textView.append(line);



}

}


catch (Exception e) {


System.out.println("Nay, did not work");


textView.setText(e.getMessage());

}

Loading data from Internet takes time, use progress dialogs while loading data as
required

Handling HTTP Calls


HttpClient cannot be executed in the main
thread


NetworkOnMainThreadException thrown


Use a Thread or AsynchTask for creating and
executing request

Sabancı University, Copyri
g
ht 2009

Post Request


In order to send form data HttpPost object
must be created


Parameters can be set as below:

Sabancı University, Copyri
g
ht 2009

HttpClient client = new DefaultHttpClient();

HttpPost request = new HttpPost("http://…/Tester/rest/myservice/saveos");


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("name", “value”));

nameValuePairs.add(new BasicNameValuePair("history",”value”));


request.setEntity(new UrlEncodedFormEntity(nameValuePairs));


HttpResponse response = client.execute(request);


Using HTTP Session


Session cookies are stored in
DefaultHttpClient object


If making a call to a session starter service,
for the following request DO NOT create a
new client but use the existing one


This way the session variables will be send to
the server with the request

Sabancı University, Copyri
g
ht 2009

Parse Json Data


Getting data from a Json web service requires an
HTTPclient and same operations in HTTP access


Then we use the built in Json objects to parse data


If Json data is mapped with object names we use a
JsonObject, else we use JsonArray

Sabancı University, Copyri
g
ht 2009

JSONArray arr = new JSONArray(result);


for (int i = 0; i < arr.length(); i++) {


JSONObject current = arr.getJSONObject(i);


Director d = new Director();


d.setName(current.getString("name"));


d.setLastname(current.getString("lastname"));


d.setId(current.getInt("id"));


directors.add(d);







}

String containing
JsonData

Consuming Soap Web
Services


Soap operations are not implemented by
default in Android


You need to use a third party implementation:
Ksoap 2


Download the library from the following link:


https://code.google.com/p/ksoap2
-
android/wiki/HowToUse?tm=2


Add the jar under /lib

Sabancı University, Copyri
g
ht 2009

Using KSoap
-
1


Create a SoapObject providing namespace
and method name



METHOD_NAME: Name of the service method
defined with “operationName”


NAMESPACE: Target Namespace of SOAP
document

Sabancı University, Copyri
g
ht 2009

SoapObject request = new SoapObject(
“http://service.com/
”,”getOsById”)

Using KSoap
-
2


Create property objects for method
parameters and add the list of parameters to
the SoapObject

Sabancı University, Copyri
g
ht 2009


PropertyInfo quotesProperty = new PropertyInfo();


quotesProperty.setName("id");





quotesProperty.setValue(Integer.valueOf(txtid.getText().toString()));

//quotesProperty.setType(int); //optional

request.addProperty(quotesProperty);

Using KSoap
-
3


Create a serialization envelope and set
SoapObject for output object

Sabancı University, Copyri
g
ht 2009

SoapSerializationEnvelope envelope = new

SoapSerializationEnvelope(SoapEnvelope.VER11);






envelope.setOutputSoapObject(request);

default envelope version

SoapObject

Using KSoap
-
4


Create an HTTPTransportSE object with
WSDL path and call()

Sabancı University, Copyri
g
ht 2009

HttpTransportSE httpRequest = new HttpTransportSE(URL);

WSDL Path


httpRequest.call(SOAP_ACTION, envelope);

SoapSerializationEnvelope

Full service address appended by “/[METHOD_NAME]”

ex:

http://10.36.52.65:8080/Tester/OperatingSystemsService/GetQuote


Parsing Soap Response


The result will be saved in the body of
envelope object


Standard objects will be kept as SoapObject,
primitive types will be kept as SoapPrimitives


Sabancı University, Copyri
g
ht 2009


httpRequest.call(SOAP_ACTION, envelope);

SoapObject result = (SoapObject)envelope.bodyIn;

SoapObject resultObj = (SoapObject)result.getProperty(0);

SoapPrimitive primType =

(SoapPrimitive)resultObj.getProperty("name");

String name = primType.toString();

Single Object returned

Accessing the “name” field in the single object

Best Practices


Soap transfers more data and requires more
processing than JSON


Try using restful web services and JSON for
data exchange

Sabancı University, Copyri
g
ht 2009