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
Related
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.
I've recently been working on an Android app using Android Studio which is using a Django backend. The web application is already in place I just want to make the app in Android for it.
The problem I am running in to, which is mostly because I'm new to app development, is the login authentication. I've researched on this topic here and I understand theoretically how I should go about doing this, but I have not been successful in logging in from my app.
The problem I have is this:
I get a csrf token authentication failure. It states that the cookie is not set. I understand that a post request will return this.
I am always getting a success transition in my doPost method.
I currently am lost in how to check if I have actually logged in or not. And the only solution I thought of for the cookie not being set is to do a Get request, parse the cookie as a string and pass that in to the post request. But I'm not sold on it being the best strategy. The bigger problem is not being able to tell if I have actually logged in or not. How can I check that? I have read posts on kind of explaining how to do this but as a beginner it is hard to translate that to code. How do I check if the user was actually authenticated? Any and all help is appreciated.
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", mEmail));
postParameters.add(new BasicNameValuePair("password", mPassword));
String response = null;
String get_response = null;
try
{
response = SimpleHttpClient.executeHttpPost(localLoginUrl, postParameters);
Log.d("Login Activity","Post Response is: " + response);
}
catch (Exception e)
{
Log.d("Login Activity","Error is: " + e.toString());
e.printStackTrace();
return false;
}
return true;
}
public static String executeHttpPost(String url,
ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The Django view:
def login_view(request): # Login page view
form = login_form()
if request.method == 'POST':
form = login_form(request.POST)
if form.is_valid(): # check if form is valid
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']) # authenthicate the username and password
login(request, user) # login the user
# Once logged in redirect to home page
response = HttpResponseRedirect("/"+some_user_url+"/home")
print "USER KEY IS: %s" % some_user_key
response.set_cookie('some_user_key', value=some_user_value, max_age=some_max_age, secure=SESSION_COOKIE_SECURE, httponly=False)
return response
else:
form = login_form() # Display empty form
return render(request, "login.html", { # loads the template and sends values for the template tags
'form': form,
})
I know the questions was asked quite a long time ago but, since there's no answer, and I'm working quite intensively with Django recently, I thought to share my very basic knowledge, hoping it will be of help for others.
The way you are dealing with the CSRF token is the correct one: first you perform a get of the login page which will give you the CSRF token in the cookie. You store the cookie and the CSRF token and you embed them in the following POST request, together with authentication data. If you get a 200 OK from the server it already means you correctly used the CSRF token, and this is an awesome start :)
In order to troubleshoot whether the user has actually logged in or not, that is whether it's credentials were accepted, you can print out the payload of the HTTP response you obtained from the server.
I use a function which prints me the response of the server in case I get an error code greater than 400. The code is the following:
public static boolean printHTTPErrorMsg(HttpURLConnection c) {
boolean error = false;
StringBuilder builder = new StringBuilder();
try {
builder.append(c.getResponseCode());
builder.append("\n");
builder.append(c.getResponseMessage());
System.out.println("RESPONSE CODE FROM SERVER");
System.out.println(builder);
InputStream _is;
if(c.getResponseCode()>=400){
error = true;
_is = c.getErrorStream();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(_is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return error;
}
You need to tweak it because when you get a 200 OK from the server, there's no ErrorStream but simply an InputStream. So if you change your if condition to =200 and replace the getErrorStream() with getInputStream() you'll see in the log what is actually the content of the response of the server. Typically, if the login failed, the response will contain most likely the HTML code of the login page with the error message saying you provided wrong credentials.
Hope this helps
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.
I want to fetch some data from a server protected with an username and password . I know both the username and password . Since the server is live , the data is continuing changing I need to fetch data every minute to update the application's status . The only function I know that can fetch data and turn it to a string is :
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://mywebsite.me");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
Since the server has a logon screen I don't know how to get pass it . So , i'd like help with 2 thigs :1. getting the data from the server and 2. every 1 or 2 minutes I need to refresh my app and fetch again the data .
You can try this for the post object. Pre-emptive authentication is done this way.
HttpPost post = new HttpPost(url);
// Prepare the authentication.
String usernameAuth = "u";
String passwordAuth = "p";
post.addHeader("Authorization", "Basic " +
Base64.encodeToString((usernameAuth + ":" + passwordAuth).getBytes("UTF-8"),
android.util.Base64.NO_WRAP));
For running this at regular intervals :
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// What you want to do goes here
}
}, 0, REFRESH_TIME);
I hope it helps.
Hi
I am trying to build a little rest client in android. I simply tries to obtain an xml file which can be parsed later on. However I have some encoding problems.
Special characters like ø and å are not recognized. The xml file uses ISO-8859-1 encoding but i cannot really figure out how to force the httpclient to use this encoding. Anyone that is able to help?
Here is the code:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
String URL = "http://konkurrence.rejseplanen.dk/bin/rest.exe";
String result = "";
Button btn;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tvResponse);
btn = (Button)findViewById(R.id.btnMakeRequest);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String query = "/departureBoard?id=8600626&date=19.03.11&time=07:02&useBus=0";
callWebService(query);
}
});
}
public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
tv.setText(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i("test", result);
}
}
thanks in advance.
best regards, kenneth
I would take a look at the response's headers. The response will need to set :
Content-Type: text/xml; charset:ISO-8859-1;
Otherwise, my understanding is that the http client will default encode to utf-8. You may also need to adjust the header on your request if your web service is using it to try and determine what you want. The thing to know is, if you do this in a browser do you get back the iso document or a utf-8 one?
HTTPGet extends this class with header methods
Source info on xml encoding