How to make requests to a web page from an Android app - android

There is a web page that has a web service which sends text messages to mobile devices, the service is not my property, I do not know the source code and therefore I do not know how it is handled internally, in that page a form is filled out and When you click on the button to send this, send the form to the server so that the information is processed.
I need to pass this web service to an android app to send this type of requests to the page from the app.
Another doubt that I have the data structure, when clicking with the mouse on the page I have obtained this code that supposedly contains the data structure but I can not find exactly which are the mobile number, the mail account and the message
The data structure is:
server=gsps.ashx
name="to" value="+8707712345678"
name="reply_email" value="qq#qq.com"
name="message" value="Hola Mundo"
I have tried to implement this using httpHandler but I do not know how to verify that the message has been sent and I can not capture the server's answer either, someone tell me how to do it.
Here the httpHandler class:
public class httpHandler {
public String post(String posturl){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("to","+870776458585"));
params.add(new BasicNameValuePair("reply_email","qq#qq.com"));
params.add(new BasicNameValuePair("message","Hola Mundo!"));
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();/*y obtenemos una respuesta*/
String text = EntityUtils.toString(ent);
return text;
}
catch(Exception e) { return "error";}
}
}
Here the MainActivity:
public class MainActivity extends AppCompatActivity {
private TextView mDumpTextView;
private ScrollView mScrollView;
private EditText mTextoEditor1;
private Button mBotonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
mBotonSend = (Button) findViewById( R.id.bt2_SendButton );
mBotonSend.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
httpHandler handler = new httpHandler();
String txt = handler.post("https://gsps.ashx");
}
} );
}
}

You can parse it if this text is come in JSON then you can use it.
Html.fromHtml("Your string");

Why don't you just load webview.Create a webview in your layout file and load the webview with your required URL.

Related

How to login and keep cookie for later use of a webpage

So, I have this webpage which I want to access, but first I have to login from another webpage. I want to keep the cookies and then use it for later automatic login. So far what I did:
First, this is the login webpage: https://autenticacao.uvanet.br/autenticacao/pages/login.jsf
It's my university's student's area.
public class Consulta extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(100000);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urls[0]);
try {
List<NameValuePair> val = new ArrayList<NameValuePair>(2);
val.add(new BasicNameValuePair("form:usuario", "myusername"));
val.add(new BasicNameValuePair("form:senha", "mypass"));
httpPost.setEntity(new UrlEncodedFormEntity(val));
HttpResponse response = client.execute(httpPost);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
}
This is the class I use to make the HttpPost and this is how I call it:
#Override
public void onClick(View v) {
try{
String html = new Consulta().execute("https://autenticacao.uvanet.br/autenticacao/pages/login.jsf").get();
Document doc = Jsoup.parse(html);
Element link = doc.select("title").first();
String t = link.text();
tv1.setText(t);
}catch(Exception e){
e.printStackTrace();
}
}
I believed it would work this way:
I send the webpage to login to Consulta.java
The class would get the fields "form:usuario" and "form:senha" and fill them with myusername and mypassword and then login
The class would return me html code of the second webpage as string
But what happens is that it returns me the first webpage (the login one). I'm pretty sure I'm doing something wrong, but I don't know what, could someone help me? Also, sorry for my english, it's not my main language.
When you do the login (in https://autenticacao.uvanet.br/autenticacao/pages/login.jsf), I don't think the response is the html code of the second webpage. Are you sure about this?
I think the normal behavior for a login page is to respond with the same page (the login one) but adding the session cookie and the header to do a redirect to the second webpage, but not the second page itself.
In this case, you have to read the http header response to extract these parameters: the cookies and the URL of the second webpage.
Using the object HttpResponse:
Header[] h = response.getAllHeaders();
But I recommend you to use HttpURLConnection class instead of DefaultHttpClient.

How to Authenticate android app with tomcat sever?

I am working on an application where I want to send an HTTP post to my Tomcat sever. In this post,I want to send the user-id as well as password and after successful authentication from TomCat it will respose to my app, I
I want next-page to display in my emulator?
Any procedure or framework on this aspect ...that I have to use.
I am posting the code to post the request and get response.
public class Register extends Activity
{
public static final String PREFS_NAME = "LoginPrefs";
public static final String USER_NAME = "USER";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText(getPage());
}
private String getPage()
{
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.yahoo.com");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
}
Now u help me with how to send data with request and server will check the incoming data if data is present in database that will ensure that user is a valid user and send some response depending on that response i will navigate to next page.
How will do this? Please help since i am new to java and android.
take a look at this first response from a google search here

Create a cache for android application

I am developing an android application which aim is to send some datas to the server. However, sometimes there may not have wifi connection, so I would like to ask if it is possible to create a cache to store multiple sets of data, say maybe 3 sets, and then the app will send those datas automatically when a connection is available.
Here is the way I send my datas to server recently:
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
#Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
//client.execute(post);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
I think Cache data is simple, you can store it in memory or store them as files. You can listen the network state change events to be notified when there is a connection available.
Here is the Sample Code.
this may be helpful in having abstract caching lib for object+image caching;
generic-store-for-android >>
To store primitive things, you can simply use SharedPreferences, and as soon as network becomes available, you can check if something with a specific key exist in SharedPreferences. If you don' t write the data inside a persistent environment(like SharedPreferences, Sqlite, file inside SD card or internal storage, etc.) closing the application will cause your data to be loss.

HTTP Post Encoding

What I try to do
Hello Guys,
I try to create a login for my server, that I can access the data on it over my app. For this i created a Methode called 'public void doLogin(final String username, final String password)' . In this Methode I start a Thread in which I post the username and password to my server. Now to problem starts. When I do the post my server can't handle my post which looks like this: '"username="+username+"&password="+password'.
To try if its a serverside problem (infact its not) I made a post over 'curl -d' with the same parameters and I get a response without any problems.
For your information the server runs on Ruby3
Question
How do I need to change my Post to the server that it can handle the data I send. By the way the string I post must look exactly like that: '"username="+username+"&password="+password //this means username=LEUSER&password=LEPASS'
Please tell me what I need to change, some code snippets or tutorials would be great. Down here you find the importrent codesnippets of the doLogin Methode
Code
public void doLogin(final String username, final String password) {
Thread t = new Thread() {
public void run() {
String URL = "http://192.168.110.126:3000/sessions.json"; //für momentane testzwecke
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity("username="+username+"&password="+password);
post.setEntity(se);
response = client.execute(post);
if (response != null) {
//response handling
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Please Guide me Regarding This.
Your code looks like you are sending a html form. In fact curl adds a content-type (with value application/x-www-form-urlencoded) to the http header if you use the -d option.
So try to add the header field like this:
HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type","application/x-www-form-urlencoded");
...
What you need to change is the String entity part. You should change with the following;
ArrayList<NameValuePair> requestParameters = new ArrayList<NameValuePair>();
requestParameters.add(new BasicNameValuePair("username", username));
requestParameters.add(new BasicNameValuePair("password", password));
username & password are the variables that are input on the program.
Lastly, if you forget to set permission it also won't work. You need to set android.permission.INTERNET

Submit form with POST data in Android app

I've been searching the web for a way to do this for about a week now, and I just can't seem to figure it out.
I'm trying to implement an app that my college can use to allow users to log in to various services on the campus with ease. The way it works currently is they go to an online portal, select which service they want, fill in their user name and pwd, and click login. The form data is sent via post (it includes several hidden values as well as just the user name and pwd) to the corresponding login script which then signs them in and loads the service.
I've been trying to come at the problem in two ways. I first tried a WebView, but it doesn't seem to want to support all of the html that normally makes this form work. I get all of the elements I need, fields for user and pwd as well as a login button, but clicking the button doesn't do anything. I wondered if I needed to add an onclick handler for it, but I can't see how as the button is implemented in the html of the webview not using a separate android element.
The other possibility was using the xml widgets to create the form in a nice relative layout, which seems to load faster and looks better on the android screen. I used EditText fields for the input, a spinner widget for the service select, and the button widget for the login. I know how to make the onclick and item select handlers for the button and spinner, respectively, but I can't figure out how to send that data via POST in an intent that would then launch a browser. I can do an intent with the action url, but can't get the POST data to feed into it.
So here is what I have right now...
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(action);
String endResult = null;
try
{
post.setEntity(new UrlEncodedFormEntity(myList));
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
String response = client.execute(post, new BasicResponseHandler());
endResult = response;
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
So my question now... is how do I take the endResult screen, which should be the page returned after I logged in to my service, and display it in a browser?
What's wrong with them just using the built in browser? You can also submit a form using UrlEncodedFormEntity and HttpClient.
HttpParams params = new DefaultHttpParams(); // setup whatever params you what
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost("someurl");
post.setEntity(new UrlEncodedFormEntity()); // with list of key-value pairs
client.execute(post, new ResponseHandler(){}); // implement ResponseHandler to handle response correctly.
Okay and after you have the response in a string. The response since its a page is going to be in html. You need to use a WebView to show the html. WebView has a method loadData() that takes a string of html and displays it.
Based on #RobbyPonds answer, for the benefit of people wandering past here, below is a generic implementation to post and receive a response from a URI (NOTE Also contains waiting implementation to return a response, probably not every day implementation of network call):
private static String responseValue;
#SuppressWarnings({ "unchecked", "rawtypes" })
public static String sendPostToTargetAndWaitForResponse() throws ClientProtocolException, IOException {
final Thread currentThread = Thread.currentThread();
synchronized (currentThread) {
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(HTTP_POST_URI);
// List Creation with post data for UrlEncodedFormEntity
ArrayList<NameValuePair> mList = new ArrayList<NameValuePair>();
mList.add(new NameValuePair() {
#Override
public String getValue() {
return getSampleJSON();
}
#Override
public String getName() {
return "json";
}
});
post.setEntity(new UrlEncodedFormEntity(mList)); // with list of key-value pairs
client.execute(post, new ResponseHandler(){
#Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
synchronized (currentThread) {
currentThread.notify();
}
return null;
}
});
try {
currentThread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return responseValue;
}
}

Categories

Resources