Pages

Showing posts with label webservice. Show all posts
Showing posts with label webservice. Show all posts

Sunday, 4 August 2013

Cosume PHP(POST METHOD) webservice in android.



Here i am passing json string parameter to php webservice. To consume php post method we will use HttpPost.

To create JSON String in android:

JSONObject json = new JSONObject();

json.put("name", "");
json.put("email", "");
json.put("password", "");

Log.i("json Object", json.toString());

Pass the parameter to post method:

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

        params.add(new BasicNameValuePair("userinfo", json.toString()));

Get the response InputStream like this:

HttpResponse response;
InputStream is = null;

   response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();

Full Code:

HttpResponse response;
JSONObject json = new JSONObject();
String json1 = "";
JSONObject jObj = null;
InputStream is = null;

DefaultHttpClient client = new DefaultHttpClient();

try {
HttpPost post = new HttpPost(
"Your URL");
json.put("name", "");
json.put("email", "");
json.put("password", "");

Log.i("jason Object", json.toString());
post.setHeader("userinfo", json.toString());

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userinfo", json.toString()));

post.setEntity(new UrlEncodedFormEntity(params));
response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();

try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json1 = sb.toString();
Log.i("jason Object", sb.toString());

Log.e("JSON", json1);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json1);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String

Log.d("final Response", jObj.toString());
Log.d("status", jObj.getString("status")); //Declare your status or message or json string variable

} catch (Exception e) {
e.printStackTrace();
}

HttpResponse to String android

Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

Note:
In AVD to connect to localhost you need to use urlhttp://10.0.2.2/ instead of http://localhost/.

Thursday, 1 August 2013

Uploading file to webservice using KSOAP


1st step: Get the file from the SDcard and assign that file in INPUTSTREAM.
2nd step: Write the file into BYTEARRAYOUTPUTSTREAM
3rd step: Convert that Stream into BYTEARRAY
4th step: Convert Bytearray into BASE64STRING


Coding

   final String SOAP_ACTION = "";//Your soap action
final String METHOD_NAME = "";//Your method name
final String NAMESPACE = "";//Your name space
final String URL = "";//Your url

                InputStream is = null;

try {
is = new BufferedInputStream(new FileInputStream(
Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/download/"
+ yourfilename));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

//http://ricky-tee.blogspot.in/2012/06/converting-from-file-to-byte-array.html?showComment=1362738218958#c5250835248744198937

ByteArrayOutputStream bos = new ByteArrayOutputStream();

                               try {
while (is.available() > 0) {
bos.write(is.read());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

byte[] byteArray = bos.toByteArray();
                             
                                String base64= Base64.encodeToString(byteArray,
Base64.DEFAULT);

      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  request.addProperty("str", base64);
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
String str = response.toString();
                                     } catch (Exception e) {
e.printStackTrace();

}          

For Reference.

Downloading file from webservice using KSOAP

Here is the code to download the file from webservice.

Coding:

                final String SOAP_ACTION = "";//Your soap action
final String METHOD_NAME = "";//Your method name
final String NAMESPACE = "";//Your name space
final String URL = "";//Your url


                                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                                //If you have some parameter to pass
//request.addProperty("", "");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();

String str = response.toString();

                                        //converting string to byte[]

byte[] decodedString = Base64.decode(str, Base64.DEFAULT);

                                  
File direct = new File(
Environment.getExternalStorageDirectory()
+ "/Download/");

if (!direct.exists()) {
direct.mkdir();
}

File file = new File(
Environment.getExternalStorageDirectory()
+ "/Download/", yourfilename);
    
if (file.exists()) {
file.delete();
}
                                              
try {
                                        //http://stackoverflow.com/a/7982964/1835764

FileOutputStream fos = new FileOutputStream(
file.getPath());

fos.write(decodedString);
fos.close();
                                             } catch (java.io.IOException e) 
                                             {
Log.e("fileDemo", "Exception in fileCallback", e);
}
}

catch (Exception e) {
e.printStackTrace();
}
}

}

Friday, 26 July 2013

Cosume PHP(GET METHOD) webservice in android.

Here i am going to show you the exact code for cosume php webservice in android. But in this example i have passes emailid and password in the url to check whether the user is valid or not.
To consume php get method we will use HttpGet.

Get the response InputStream like this:

InputStream is = null;

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

Full Code:

  InputStream is = null;
JSONObject jObj = null;
String json = "";

       //Place your own url here
String URL = "http://domain.com/login.php?email="
+ username.getText().toString().trim().toLowerCase()
+ "&password="
+ password.getText().toString().trim().toLowerCase() + "";

   Log.d("username", username.getText().toString().trim()
   .toLowerCase());
   Log.d("password", password.getText().toString().trim()
   .toLowerCase());

   // Making HTTP request
   // (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/)

   try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);

Log.d("pre", URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

   } catch (UnsupportedEncodingException e) {
e.printStackTrace();
   } catch (ClientProtocolException e) {
e.printStackTrace();
   } catch (IOException e) {
e.printStackTrace();
   }

   try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
   sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
   } catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
   }

   // try parse the string to a JSON object
   try {
jObj = new JSONObject(json);
   } catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
   }

   // return JSON String

   Log.d("test", jObj.toString());


Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

convert httpresponse to string android 

Consume .net webservice in android



This simple example demonstrates how we can access a .net web service  from Android application.

 XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/web_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="112dp"
        android:layout_marginTop="146dp"
        android:text="Web Service" />

    <TextView
        android:id="@+id/fetch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

    <ImageView
        android:id="@+id/fetch_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/fetch"
        android:layout_below="@+id/fetch"
        android:layout_marginTop="52dp"
        android:src="@drawable/ic_action_search" />

</RelativeLayout>

Activity:

public class MainActivity extends Activity {

Button web_service;
TextView fetch_service;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fetch_service = (TextView) findViewById(R.id.fetch);
web_service = (Button) findViewById(R.id.web_service);
web_service.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myasynctask MAT = new myasynctask();
MAT.execute();
}
});
}

class myasynctask extends AsyncTask<String, Void, String> {

String str;
private static final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private static final String METHOD_NAME = "CelsiusToFahrenheit";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";

@Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Celsius", "32");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
str = response.toString();

} catch (Exception e) {
e.printStackTrace();

}
Log.d("WebRespone", str);
return str;
}

@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
fetch_service.setText(result);
super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}

}
}
Manifest:
add the following thins in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>

To Do:

You Must add this KSOAP jar file in your Lib folder