package
com.rest.web.services;
import
java.io.BufferedReader;
import
java.io.InputStreamReader;
import
org.apache.http.HttpResponse;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.entity.StringEntity;
import
org.apache.http.impl.client.DefaultHttpClient;
import
org.json.JSONStringer;
import
android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class
RestWebServicesDemoActivity extends Activity {
private final static String SERVICE_URI = "http://restwebservice.com/test/Service.svc";
/** Called when the
activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static void callWebService() {
try {
// make web service
connection
HttpPost
request = new HttpPost(SERVICE_URI + "/TestApplication");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON
string
JSONStringer
TestApp = new JSONStringer().object().key("id")
.value("1").key("name").value("manish").key("email")
.value("androidhub4you@gmail.com").key("country")
.value("india").endObject();
StringEntity
entity = new StringEntity(TestApp.toString());
Log.d("****Parameter
Input****", "Testing:" + TestApp);
request.setEntity(entity);
// Send request to
WCF service
DefaultHttpClient
httpClient = new DefaultHttpClient();
HttpResponse
response = httpClient.execute(request);
Log.d("WebInvoke", "Saving:
" +
response.getStatusLine().toString());
// Get the status
of web service
BufferedReader
rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// print status in
log
String
line = "";
while ((line =
rd.readLine()) != null) {
Log.d("****Status
Line***", "Webservice: " + line);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Status Line = http/1.0 404 not found
ReplyDeletewhat to do with this?
and not getting proper response from server
That mean your server url is wrong..
ReplyDeleteHit on browser it should return code-200
i used this thing with my facebook login application. but now i want to use it with asynctask method. most of the tutorial are confusing. will you upload a sample code which work with asynctask method with web services
ReplyDeleteHi Just put this code inside do in background in async class, follow my this blog-
Deletehttp://www.androidhub4you.com/2013/03/main-thread-issue-in-android-async.html
Hello Manish,
ReplyDeleteThis is Pradeep, Nice tutorial. Thanks for this useful blog. Can you plz upload also the layout codes for your further posts...
Thnx.
Yes sure I will mind it next time..
DeleteBut in this post nothing in layout, you can call any layout..
Hi Manish I Need Help from u.I am getting HTML Page Response
ReplyDeleteI have a URL:http://stressisgone.com/members/users.json
parameters:
Registration
-------------
email
first
last
zip
password
confirm
Login(same URL)
-----
email
password
Problem with your url. I don't think it is .json , it may be .php, .svc, .asp or someting else according which type of service you are using.
DeleteAnd if it is get service you can test in browser also.
And you can try combination of "?" With your service url like- xyz.php?name=manish&email=xyz
Etc...
Hi manish can u please tel me how to test this REST based webservies in android. If you have example can u post. Thank you
DeleteHi Praaveen!
DeleteAbove code for client side(Android) so just right REST full web-services for testing the demo. You can use any language (java, php, .net) for write web-services.
Hi Manish,
ReplyDeleteWhat should be the url in this case. I am unable to open the webpage http://localhost:8080/wifidirect.txt. I need to post these details in above webpage. what exactly i am missing?
public class LongOperation extends AsyncTask {
protected Void doInBackground(String... urls) {
Log.d("LongOperation:::","doInBackground mtd") ;
try {
HttpClient client = new DefaultHttpClient();
//Timeout Limit
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
JSONObject json = new JSONObject();
HttpPost post = new HttpPost("http://localhost:8080/wifidirect.txt");
json.put("email", "ss@gmail.com");
json.put("password", "22445");
Log.d("json value::",json.toString());
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
Log.d("client response::: ","after executing response");
Log.d("samba's Response:::","is not null");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return null;
}
adb logcat output
D/****Status Line***( 2479): Webservice: The requested resource does not exist on this server.
Hi Sam,
DeleteI feel your URL is wrong. in which language you have written your web-service? .txt is not any format I think, its indicate text file. it should be .php, .aspx or any other script language. I think that's why you are getting that issue-
The requested resource does not exist on this server
hi, I take error as -> "The server encountered an error processing the request. See server logs for more details."
ReplyDeletepublic void excutePost(JSONObject json){
// make web service connection
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(SERVICE_URI + "/SaveAgent");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
try {
entity = new StringEntity(json.toString());
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
// Get the status of web service
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
your web-service in which language written? .net,php,java ? Basically this is a Rest-full web-service for .net.
DeleteHi Manish,
ReplyDeleteIn my App I have 2 activity I want if the application run first time then activity 1 show but if application already run 1 times then if user launch application then activity 2 is directly open.
For this use shared preferences like this-
Delete1)make variable-
boolean isFirstTime;
SharedPreferences app_preferences;
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
isFirstTime = app_preferences.getBoolean("isFirstTime", false);
2)Now check it for first login-
if (isFirstTime == false){
SharedPreferences.Editor editor = app_preferences.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
Intent intent = new Intent();
intent.setClass(SplashActivity.this,
FirstPage.class);
startActivity(intent);
}
else{
Intent intent = new Intent();
intent.setClass(SplashActivity.this,
SecondPage.class);
startActivity(intent);
}
Hi Manish,
ReplyDeleteThis is much required for me, Is there any way to like facebook page on button click without redirecting user to facebook page.anyone who have idea about this can reply.
With out one time login on Facebook you can't. It is Facebook security policy, ones you have to allow user to do it. You can do one thing force user to login with Facebook account first time and keep his credential in preference for next time use.
Deletethanks for reply,
DeleteLogin is not issue for me, if user is already login using facebook then how to enable auto like on button click without user interaction with facebook page.
Can we call the POST services of wcf with this code.. I coudn't be able to get the response using the POST service call. i am getting the null response? how can i call it?
ReplyDeleteit really means alot to me .
ReplyDeletethank you