Android : How to access web page and send parameters to it - android

I am developing an android application and i need to access the server side which is done as web pages in asp.net
below is the web page URL :
theWebPageURL?action=methodName&email=theEmail
i don't know what methods shall i use to access this URL and send the email parameter to it and get the response.
i searched alot and none worked
can anyone help me please ?

I would recommend reviewing these two similar qustions:
Make an HTTP request with android
How to add parameters to a HTTP GET request in Android?
UPDATE
The below code is a working sample I put together based off of the answers in the two links above; if this helps you, be sure to thank them.
For demonstration, the uri in this sample is being constructed into http://www.google.com/search?q=android.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Construct the URI
String uri = "http://www.google.com/search?";
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("q", "android"));
uri += URLEncodedUtils.format(params, "utf-8");
// Run the HTTP request asynchronously
new RequestTask().execute(uri);
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result contains the response string.
}
}
}
And, of course, don't forget to add this to your manifest:
<uses-permission android:name="android.permission.INTERNET" />

You need to use http get request
HttpGet
and add this line to your manifest file
<uses-permission android:name="android.permission.INTERNET" />
also, check this link

Related

Proper way to call web service using rest in android?

Please suggest any solution?
I'm new to android.I'm getting error while invoking web service
W/System.errīš• java.io.IOException: Method Not Allowed
Here is my activity which calls a web service(method) which takes one string parameter and gives output. I'd be glad if anybody posts code snippet using asynctask becos it is most preferred way to call service in android....
public class closingBalance extends ActionBarActivity {
protected final String NAMESPACE = "http://xxxxx/";
protected final String METHOD_NAME = "getReportDetails";
protected final String URL = "http://xxxxx?wsdl?shop_num=12345";
HttpClient client = new DefaultHttpClient();
try {
HttpResponse res = client.execute(new HttpGet(URL));
StatusLine line = res.getStatusLine();
if(line.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
res.getEntity().writeTo(out);
String response = out.toString();
System.out.println(response);
out.close();
}else{
res.getEntity().getContent().close();
throw new IOException(line.getReasonPhrase());
}
} catch (IOException e) {
e.printStackTrace();
}
}
I advise you to research the Volley tool can be very useful to you.
Transmitting Network Data Using Volley is very simple
https://developer.android.com/training/volley/index.html
Consider using Retrofit library.
Here is a comparison between AsyncTask, Volley and Retrofit

How to control raspberry pi gpio ports using android app?

What methods are available in controlling the GPIO ports of a Raspberry Pi using an Android application?
I've looked at using nodejs and briefly socketio - But really am none the wiser as to how to go about implementing this technology?
Is anybody able to explain the approach in greater deal/suggest an alternative / have existing examples?
Thanks
I advise you to make the raspberry pi a webserver by using Bottle web server, then develop an android app that sends HTTP requests to the web server to control the GPIO pins. You can use this class to make http requests:
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, 0).show();
}
}
For example, to make http request when you press a button in your app. You just write inside the function:
new RequestTask().execute("http://192.168.1.145:80/3");
In my example, I am assuming that the app and the raspberry pi are connected in the same network.

Android application force Close on lowsy Internet connection

I have the following code for to perform xml download via asynctask for android application targeting for android version>3. The code work pretty good if the network/internet connection is good. However, if internet connection is not good, the application will force close. I have tried throw in different kind of error catching but still unable to solve the force close on lowsy internet connection.
Anyone has any suggestion that I can try
private class DownloadWebPageXML extends AsyncTask<String, Void, InputStream> {
#Override
protected InputStream doInBackground(String... urls) {
Log.d("mylogitem", "AsyncTask started!");
InputStream content = null;
String myurl = urls[0];
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
HttpGet httpGet = new HttpGet(myurl);
try {
HttpResponse execute = client.execute(httpGet);
content = execute.getEntity().getContent();
} catch (Exception e) {
xmldownloaderror = e.getMessage();
Log.d("mylogitem", e.getMessage());
} finally {
Log.d("mylogitem", "Closing AndroidHttpClient");
client.close();
}
return content;
}
#Override
protected void onPostExecute(InputStream result) {
//do xml reader on inputstream
}
}
add a null check on variable execute, in between these two lines
HttpResponse execute = client.execute(httpGet);
if(execute == null){ return null;} // null check to see if execute is null
content = execute.getEntity().getContent();
another thing in onPostExecute, first line should check if InputStream result is null!
#Override
protected void onPostExecute(InputStream result) {
if(result == null){
Log.d("TEMP_LOG",Content is null);
return;
}
//do xml reader on inputstream
}
check and post your findings
hmm... I recommend to set connection times.
HttpClient client = new DefaultHttpClient();
HttpResponse response;
BufferedReader bufferedReader = null;
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 20000);
I have found the root cause. It is not in the dobackground.
In my case, lousy connection will sometime return not xml data type but rather loading error,
and this is passed as the inputstream to my xmlparser in postexecute.
I did not put in much error catcher in my xmlparser. xmlparser is expecting xml document but received non-xml content, thus throwing null in which i did not cover with error catcher.
Thank you for the suggestion. I have place it in my code as well.

How to send a HTTP Post request from my android project to google app engine?

I am working on an android project. I am new in android programming. How can i send a HTTP post request from my project to google app engine? I searched and found this code for sending request from android but its not working. Following is the code i am using:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/servleturl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", userEmailStr));
nameValuePairs.add(new BasicNameValuePair("password", userPasswordStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
info.setText(response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Thanks for help in advance.
Here's the class that i use for http requests in java:
public class WSConnector {
final String baseUrl = "http://www.myURL.com/"; //this is the base url of your services
String realUrlWithParams="";
String realUrl="";
String params = "";
String charset = "UTF-8";
HttpURLConnection connection = null;
public WSConnector(String serviceName,String params,String charset){ //we create the connector with everything we need (params must be ready as value pairs, serviceName is the name of your service):
if (charset!=null){
this.charset = charset;
}
this.realUrlWithParams = baseUrl+serviceName+"?"+params;
this.realUrl = baseUrl+serviceName;
}
public String getResponse(){//getResponse will get your the entire response String
String result = "";
System.out.println("trying connection");
try {
connection = (HttpURLConnection) new URL(realUrlWithParams).openConnection();
//connection.setRequestProperty("Accept-Charset", charset);
int status = connection.getResponseCode();
System.out.println("status:"+status);
if (status==HttpURLConnection.HTTP_OK){
InputStream responseStream = connection.getInputStream();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(responseStream));
for (String line; (line = reader.readLine()) != null;) {
System.out.println("line is:" +line);
result = result+line;
System.out.println("result is:"+result);
}
}
} catch (MalformedURLException e) {
System.out.println("ERROR IN CONNECTOR");
e.printStackTrace();
} catch (IOException e) {
System.out.println("ERROR IN CONNECTOR");
e.printStackTrace();
}
System.out.println("finished connection");
return result;
}
if wanting to know some more, visit this CW:
httpurlconnection
I didn't give permission to user of my app to use internet. For doing that we just need to add this line in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
Use restlet (http://wiki.restlet.org/docs_2.0/13-restlet/21-restlet.html) on app engine to handle the http requests as they come in. This isn't typically how app engine is used, but it'll work for what you want.
In andoid, just do a normal http request (http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java) on the appropriate url.
You should be able to figure out how to setup the url from the restlet tutorial. Once you deploy to app engine, the url will be something like http://myapp.appspot.com/goodstuff
Good luck!

Send HttpPost with Async and get string result

I am relatively a new Android developer and I am not able to understand how to do this. I have been looking through all the forums, I made some advance but still here I am.
So, what I want to do is a common function that send a POST request to a webpage (it only sends one POST argument) and returns the result as a string.
I have the main thread here
public class AppActivity extends Activity {
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText(PostData.Result);
}
and I have my HTTPPostData asynchronous class
public class HTTPPostData extends AsyncTask<String, Long, Object> {
String Value = null;
String Result = null;
public HTTPPostData(String query) {
Value = query;
}
#Override
protected String doInBackground(String... params) {
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mypage.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("cmd", Value));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return Result;
}
}
I want to use this function several times (inside the same Activity or share it with other Activities of the same application). I am a little bit messed up at this moment so I need your help. What I understand is that I am asking for the result before the doInBackground() is done, and I get an empty result.
Thanks in advance for your help
Regarding this:
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText(PostData.Result);
Your problem is that you're treating asynctask like it's just a regular function. It's good that you move webpage loading off the main thread, but if you depend on the result for the very next instruction, then it's not doing you much good, you're still blocking the main program waiting for the result. You need to think of AsyncTask like a 'fire and forget' operation, in which you don't know when, if ever, it will come back.
The better thing to do here would be something like:
HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText("Loading...");
and then in the asynctask:
protected void onPostExecute(String result) {
txtLabel.setText(result);
}
This lets your main thread get on with doing it's business without knowing the result of the asynctask, and then as soon as the data is available the asynctask will populate the text label with the result.

Categories

Resources