Receiving data from Android in a ASP.NET web site - android

I wrote an Android app that sends data to an ASP.NET web site. When I test the app, I get the error:
Connection to https://localhost:1863 refused.
How do I solve this problem? Also, how do I go about storing this data into SQL Server?
HttpClient client1 = new DefaultHttpClient();
HttpPost request = new HttpPost("http://localhost:1863");
String lat = "lat",lng = "lng";
List<NameValuePair> postParameters = new ArrayList<NameValuePair>(3);
postParameters.add(new BasicNameValuePair("lat", lat));
postParameters.add(new BasicNameValuePair("lng", lng));
try {
request.setEntity(new UrlEncodedFormEntity(postParameters));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
// request.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response;
response = client1.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
String page = "";
line = in.readLine();
while (line != null)
{
page = page + line;
line = in.readLine();
}
}
catch (ClientProtocolException e) {
e.printStackTrace();} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You need to get the IP address of your server, rather than using localhost, since localhost is local to the calling computer, so the localhost for the Android is different than for the IIS server.
UPDATE:
Just use IP address 10.0.2.2, as explained in Stack Overflow question How to connect to my http://localhost web server from Android Emulator in Eclipse.

I made an ASP.NET handler page (.ashx), named it Handler, and replaced "http://localhost:1863"with"http://localhost:1863/Handler.ashx" and it solved the problem.

Related

send data to website -Android

There is a website in which there are several drop down boxes.I made an android app that pulls the values from the site. Now there is a search box in the website , in the website we can choose options from the box and press submit , then it gives the result based on the options selected. I need to do the same in my app.
Need help.Thanks
To post data to a website you have send a HTTP POST request to it. You can put the data which you want to send in an array and send it to the php script.
You have to figure out with which ID your String is send to the server. In my example it is your_1 and your_2. This is different to each website. All new browsers can read this out in a developer console or something.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("your_1", "data 1"));
nameValuePairs.add(new BasicNameValuePair("your_2", "data 2"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
After you have send this you have to get the response which you can read out with a StringBuilder.
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
Now you have the response and you can emphasize your special text with RegEx. This is a little bit tricky but this will help you.

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!

Android Login to Website - Always returns login page data

I have a login form currently taking login parameters and logging into a website using HTTP Post Request. I am unsure of the server type so that could be the problem. Once it takes the login credentials, it coverts the inputstream to a string (all the html) and sets that to a textview. Here's the login:
private void postLoginData() throws ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("loginurl"); // Changed for question.
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("sid", "username"));
nameValuePairs.add(new BasicNameValuePair("pin", "pass"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String finalres = inputStreamToString(response.getEntity().getContent()).toString();
tvStatus.setText(finalres);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
And here's the inputStreamToString()
private StringBuilder inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
The problem is that it ALWAYS just returns the HTML for the login page. When a user fails login on the site, it has a little message to indicate so. Even if I add incorrect credentials, it doesn't display anything different. Likewise, if I add the correct login, it still shows me just the login page HTML.
To check for HTTP status. Do something like this
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something here.. I'm logged in.
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
// Do Something here. Access Denied.
} else {
// IF BOTH CASES not found e.g (unknown host and etc.)
}
This will exactly works as you want to check for status. thanks
I guess the problem is similar to this question. Check it out, there are some solutions, which might work for you in solving it.

UnknownHostException is thrown in android app if hostname is used instead of IP address

I have the following code which I use to send a request to the server.
String inputXML = createInputXML(searchText);
HttpClient httpclient = new DefaultHttpClient();
String url = "http://mysite.com/action";//Works fine if I use IP address directly,for eg:http://1.2.3.4/action
HttpPost httppost = new HttpPost(url);
HttpResponse response=null;
StringEntity se = null;
try {
se = new StringEntity(inputXML, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/xml;charset=UTF-8");
httppost.setEntity(se);
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I run the program on emulator I am getting a UnKnownHostException on the line
response = httpclient.execute(httppost);
If I use the ip address directly instead of host name,the request is sent correctly.
Please note the following points:
I am using Android 2.3.3
I have added <uses-permission android:name="android.permission.INTERNET"></uses-permission> in the manifest xml
Proxy settings are updated in the emulator's APN.
Using the browser in the emulator I can access a website with their host names.
Any idea why this is causing an issue?
Please make sure, you followed all steps 1-4 user700284 described in his Question.
HttpClient client = new DefaultHttpClient();
//Get the default settings from APN (could be also hard coded stuff)
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet request = new HttpGet("http://www.google.com");
The url has nothing to do with the line
se = new StringEntity(inputXML, HTTP.UTF_8);
are you sure it is this line?

Why doesn't HttpClient work but HttpUrlConnenction do when posting data to form

I'm building an android app which should perform a GET on my site to get two cookies and then perform a post to the same site with these cookies.
As mentioned I start of with the GET and I'm using org.apache.http.client.HttpClient to perform this operation.
String requiredCookies = "";
HttpContext localContext = null;
System.out.println("------------------GET----------------------");
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("www.mysitegeturl.com");
//Creating a local instance of cookie store.
CookieStore cookieJar = new BasicCookieStore();
// Creating a local HTTP context
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);
HttpResponse response;
try {
response = httpClient.execute(get, localContext);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
//Do this so that Java.net impl should work
List<Cookie> cookies = cookieJar.getCookies();
for (int i = 0; i < cookies.size(); i++) {
requiredCookies += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("------------------GET-END---------------------");
So far so good. Don't mind the requiredCookies line yet, it will be used in the Java.net impl since I can't get the HttpClient one to work =(.
Let's take a look at the non working HttpClient Post part.
System.out.println("------------------HttpClient - POST----------------------");
HttpPost post = new HttpPost("www.mysiteposturl.com");
//Params
HttpParams params = new BasicHttpParams();
params.setParameter("foo", "post");
params.setParameter("bar", "90");
params.setParameter("action", "search");
post.setParams(params);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
HttpResponse response2 = httpClient.execute(post, localContext);
System.out.println(response2.getStatusLine());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
What happens now is that I perform a POST with the localContext where the cookies are stored. This doesn't work. I get a HTTP/1.1 401 No session. Since I had no luck with this I tried another approach(java.net.HttpURLConnection). Remember I still use the same GET part
URL url = new URL("www.mysiteposturl");
HttpURLConnection connection = null;
String dataString = "bar=90&foo=post&action=search";
try {
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie", requiredCookies);
//Set to POST
connection.setDoOutput(true);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(dataString);
writer.flush();
writer.close();
connection.connect();
if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {
System.out.println(connection.getContent().toString());
} else {
System.out.println("Error");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
And VIOLA a 200 is displayed and everything works like a charm. What do you guys think? Could someone please provide me with an answer because I can't figure it out.
The problem appears to be that you have two different host names in the setup. This will cause HTTP Client to not send cookies for a different host. You could try changing the domain of the cookies in the cookie store, or using the same host for GET and POST. Additionally you could manually add the cookies to the headers in HTTP Client as you did in the HttpURLConnection example.
I guess it was a mistake that you used two completely different domains for your two requests — i.e. you were trying to mask your real URL? If not, then that's why you're not getting any cookies. If were just trying to mask your URL, well that's why example.com exists. :)
Alternatively, and this is completely off the top of my head from code I wrote last week — it worked fine across multiple GETs, POSTs and subdomains:
DefaultHttpClient httpClient = new DefaultHttpClient();
CookieStore cookieJar = new BasicCookieStore();
httpClient.setCookieStore(cookieJar);
i.e. I'm explicitly using a DefaultHttpClient, which I believe has those extra get/setters for the cookie store. I don't think I used any context objects either.

Categories

Resources