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.
Related
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!
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.
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.
I'm trying to use HTTP POST to submit user information on a University login page. To do so I run the postData() method below. The code posts the credentials and reads the response. Below the code I have shown what the response status line and response entity show. (I edited the username and password for security ;) ).
It appears to execute since I get a response from the website, but I don't know how to interpret what it says or what I need to do to have a successful login. The website in question has a username field (id = user), password field (id = pass), and login button (id = submit). It is a secure website (https), but for now I'm not doing a SSL connection as I'm just trying to get this code working.
The immediate questions I have are: is it possible I need the SSL connection to make it work, and is Java an issue as mentioned in the response?
A little more background... This is done in a service, and it's the only task. If Java is the issue, how would I enable it without a webview?
public void postData() {
// Create a new HttpClient and Post Header
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost("https://wiscmail.wisc.edu/login/");
TextView info = (TextView) findViewById(R.id.info);
EditText user = (EditText) findViewById(R.id.user);
EditText pass = (EditText) findViewById(R.id.pass);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", pass.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.v(TAG, response.getStatusLine().toString());
info.setText(response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Log.v(TAG, responseEntity.toString());
String response_string = inputStreamToString(response.getEntity().getContent()).toString();
Log.v(TAG, response_string);
} catch (ClientProtocolException e) {
Log.v(TAG, "client protocol exception");
info.setText("client protocol exception");
} catch (IOException e) {
Log.v(TAG, "IO exception");
info.setText("IO exception");
}
}
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
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
response.getStatusLine
HTTP/1.1 200 OK
response.getEntity().getContent()
<html><head></head><body onLoad="document.relay.submit()">
<form method=post action="https://login.wisc.edu/?appurl=wiscmail.wisc.edu/login"
name=relay><input type=hidden name=pubcookie_g_req
value="b25lPXdpc2NtYWlsLndpc2MuZWR1JnR3bz1XaXNjTWFpbCtMb2dpbiZ0aHJlZT0xJmZvdXI9YTUmZml2ZT1QT1NUJnNpeD13aXNjbWFpbC53aXNjLmVkdSZzZXZlbj1MMnh2WjJsdUx3PT0mZWlnaHQ9Jmhvc3RuYW1lPXdpc2NtYWlsLndpc2MuZWR1Jm5pbmU9MSZmaWxlPSZyZWZlcmVyPShudWxsKSZzZXNzX3JlPTAmcHJlX3Nlc3NfdG9rPTM5NjgzODc5MSZmbGFnPTA=">
<input type=hidden name=post_stuff value="user=username&pass=password">
<input type=hidden name=relay_url value="https://wiscmail.wisc.edu/PubCookie.reply">
<noscript><p align=center>You do not have Javascript turned on, please click the
button to continue.<p align=center><input type=submit name=go value=Continue>
</noscript></form></html>
EDIT:
Per suggestion I tried adding a setHeader to the http client, but I got the same response form the website.
httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
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
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());