Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Android AsyncTask HTTP POST
#1
C++ Code
  1. package com.example.t;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.HttpClient;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.impl.client.DefaultHttpClient;
  17. import org.apache.http.message.BasicNameValuePair;
  18.  
  19. import android.app.Activity;
  20. import android.content.Intent;
  21. import android.os.AsyncTask;
  22. import android.os.Bundle;
  23. import android.support.v4.app.NavUtils;
  24. import android.util.Log;
  25. import android.view.Menu;
  26. import android.view.MenuItem;
  27. import android.widget.TextView;
  28.  
  29. public class Action extends Activity {
  30. private TextView textView;
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_action);
  35. getActionBar().setDisplayHomeAsUpEnabled(false);
  36. Intent intent = getIntent();
  37. String user = intent.getStringExtra(Home.USER_NAME);
  38. String pass = intent.getStringExtra(Home.PASS_WORD);
  39. String dest = intent.getStringExtra(Home.END_POINT);
  40. download(dest, user, pass);
  41. }
  42.  
  43. @Override
  44. public boolean onCreateOptionsMenu(Menu menu) {
  45. getMenuInflater().inflate(R.menu.activity_action, menu);
  46. return true;
  47. }
  48.  
  49. @Override
  50. public boolean onOptionsItemSelected(MenuItem item) {
  51. switch (item.getItemId()) {
  52. case android.R.id.home:
  53. NavUtils.navigateUpFromSameTask(this);
  54. return true;
  55. }
  56. return super.onOptionsItemSelected(item);
  57. }
  58.  
  59. public void download(String endpoint, String user, String pass) {
  60. getHTML task = new getHTML();
  61. task.execute(endpoint, user, pass);
  62. textView = (TextView) findViewById(R.id.textView1);
  63. textView.setText("User: "+ user +" Pass: "+ pass +" URL: "+ endpoint);
  64. }
  65.  
  66. class getHTML extends AsyncTask<String, Integer, String> {
  67. @Override
  68. protected String doInBackground(String... params) {
  69. try {
  70. get_data(params[0], params[1], params[2]);
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. }
  74. return null;
  75.  
  76. }
  77.  
  78. protected void onPostExecute(String result) {
  79.  
  80. }
  81.  
  82.  
  83. }
  84.  
  85. public String get_data(String dest, String user, String pass) throws IOException{
  86. InputStream is = null;
  87.  
  88. try {
  89. HttpClient httpclient = new DefaultHttpClient();
  90. HttpPost httppost = new HttpPost(dest);
  91. try {
  92. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
  93. nameValuePairs.add(new BasicNameValuePair("email", user));
  94. nameValuePairs.add(new BasicNameValuePair("password", pass));
  95. nameValuePairs.add(new BasicNameValuePair("do","user_login"));
  96. nameValuePairs.add(new BasicNameValuePair("akey", "android_app"));
  97. httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  98. HttpResponse response;
  99. Log.d("http", "Dest: " + dest);
  100. Log.d("http", "User: " + user);
  101. Log.d("http", "Pass: " + pass);
  102. Log.d("http", "Device: " + System.currentTimeMillis());
  103. response = httpclient.execute(httppost);
  104. Boolean outp = request(response);
  105. if(outp) {
  106. Log.i("auth", "Login Successful");
  107. return "0x00";
  108. } else {
  109. Log.i("auth", "Login Failed with " + outp);
  110. return "0x01";
  111. }
  112. } catch (ClientProtocolException e) {
  113. e.printStackTrace();
  114. } catch (IOException e) {
  115. e.printStackTrace();
  116. }
  117. } finally {
  118. if (is != null) {
  119. is.close();
  120. }
  121. }
  122. return null;
  123. }
  124.  
  125. public static Boolean request(HttpResponse response){
  126. String result = "";
  127. try{
  128. InputStream in = response.getEntity().getContent();
  129. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  130. StringBuilder str = new StringBuilder();
  131. String line = null;
  132. while((line = reader.readLine()) != null){
  133. str.append(line);
  134. }
  135. in.close();
  136. result = str.toString();
  137. if(str.toString().equals("0")) {
  138. return true;
  139. } else {
  140. return false;
  141. }
  142. }catch(Exception ex){
  143. result = "Error";
  144. }
  145. return false;
  146. }
  147. }
crAyon makes no warranty with respect to documents or other information available from this place, assumes no legal liability or responsibility whatsoever for the accuracy, completeness, or usefulness of any such information, and does not represent that its use would not infringe privately owned rights. crAyon disclaims all warranties, express and implied, including the warranties of merchantability and fitness for a particular purpose.
Reply

#2
Code:
package com.example.t;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.workfeed.beta.R;

public class Home extends Activity {
    public final static String PASS_WORD = "com.example.t.PASS_WORD";
    public final static String USER_NAME = "com.example.t.USER_NAME";
    public final static String END_POINT = "com.example.t.END_POINT";
    private EditText inputEmail;
    private EditText inputPassword;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        
        if (getIntent().getBooleanExtra("EXIT", false)) {
            finish();
           }
      
    }

    public void error(String error, String message) {
        TextView nstatus = (TextView) findViewById(R.id.nstatus);
        nstatus.setTextSize(40);
        nstatus.setText(message);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }

    public void startNet(View view) {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                 Intent intent = new Intent(this, Action.class);
                 inputEmail = (EditText) findViewById(R.id.email);
                 inputPassword = (EditText) findViewById(R.id.password);
                 String dest = "http://workfeed.co/core/wf_auth.php";
                 String user = inputEmail.getText().toString();
                 String pass = inputPassword.getText().toString();
                 intent.putExtra(USER_NAME, user);
                 intent.putExtra(PASS_WORD, pass);
                 intent.putExtra(END_POINT, dest);
                 startActivity(intent);
            } else {
                TextView nstatus = (TextView) findViewById(R.id.nstatus);
                nstatus.setTextSize(40);
                nstatus.setText("No Network...");
            }
        
    }
    
}

Code:
package com.example.t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.workfeed.beta.R;

public class Action extends Activity {
    public TextView textView;
    public final static String USER_NAME = "com.example.t.USER_NAME";
    public final static String INVALID_PASS = "com.example.t.INVALID_PASS";
    static final int DIALOG_ERROR_LOGIN = 1;
    static final int DIALOG_OK_LOGIN = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action);
        getActionBar().setDisplayHomeAsUpEnabled(false);
        Intent intent = getIntent();
        String user = intent.getStringExtra(Home.USER_NAME);
        String pass = intent.getStringExtra(Home.PASS_WORD);
        String dest = intent.getStringExtra(Home.END_POINT);
        download(dest, user, pass);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_action, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void download(String endpoint, String user, String pass) {
        getHTML task = new getHTML();
        task.execute(endpoint, user, pass);
    }

    class getHTML extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                get_data(params[0], params[1], params[2]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

        }

        protected void onPostExecute(String result) {

        }

    }

    public String get_data(String dest, String user, String pass)
            throws IOException {
        InputStream is = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(dest);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        4);
                nameValuePairs.add(new BasicNameValuePair("email", user));
                nameValuePairs.add(new BasicNameValuePair("password", pass));
                nameValuePairs.add(new BasicNameValuePair("do", "user_login"));
                nameValuePairs
                        .add(new BasicNameValuePair("akey", "android_app"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response;
                Log.d("http", "Dest: " + dest);
                Log.d("http", "User: " + user);
                Log.d("http", "Pass: " + pass);
                Log.d("http", "Device: " + System.currentTimeMillis());
                response = httpclient.execute(httppost);
                Boolean outp = request(response);
                if (outp) {
                    Log.i("auth", "Login Successful");
                    final Intent intent = new Intent(this, Workfeed.class);
                    startActivity(intent);
                    Action.this.finish();
                    return "0x00";
                } else {
                    Log.e("auth", "Login Failed with " + outp);
                    fireAlert(1);
                    return "0x01";
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return null;
    }

    public void fireAlert(final Integer alertID) {
        Action.this.runOnUiThread(new Runnable() {
            public void run() {
                switch (alertID) {
                case 1:
                    showDialog(DIALOG_ERROR_LOGIN);
                    break;
                case 2:
                    // do the work to define the game over Dialog
                    break;
                }

            }
        });
    }

    public Dialog onCreateDialog(int id) {
        Dialog dialog;

        switch (id) {
        case DIALOG_ERROR_LOGIN:
            final Intent intent = new Intent(this, Home.class);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Error Logging In")
                    .setCancelable(false)
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    startActivity(intent);
                                    Action.this.finish();
                                }
                            });
            AlertDialog alert = builder.create();
            return alert;
        case DIALOG_OK_LOGIN:

            break;
        default:
            dialog = null;
        }
        return null;
    }

    public static Boolean request(HttpResponse response) {
        @SuppressWarnings("unused")
        String result = "";
        try {
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
            in.close();
            result = str.toString();
            if (str.toString().equals("0")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            result = "Error";
        }
        return false;
    }
}

Code:
package com.example.t;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

import com.workfeed.beta.R;

public class Workfeed extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workfeed);
        getActionBar().setDisplayHomeAsUpEnabled(false);
        TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
        tabHost.setup();

        TabSpec spec1=tabHost.newTabSpec("Latest");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator("Latest");

        TabSpec spec2=tabHost.newTabSpec("All");
        spec2.setIndicator("All");
        spec2.setContent(R.id.tab2);

        TabSpec spec3=tabHost.newTabSpec("Profile");
        spec3.setIndicator("Profile");
        spec3.setContent(R.id.tab3);

        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_workfeed, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, Home.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }
}
crAyon makes no warranty with respect to documents or other information available from this place, assumes no legal liability or responsibility whatsoever for the accuracy, completeness, or usefulness of any such information, and does not represent that its use would not infringe privately owned rights. crAyon disclaims all warranties, express and implied, including the warranties of merchantability and fitness for a particular purpose.
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  Help Android problem Yamato 12 8,185 04-25-2014, 04:49
Last Post: ScHmIdTy56789
  Post your trolls! (top 10 will be listed) 99IRock 28 13,335 01-28-2013, 12:01
Last Post: JariZ
  delte this post TITNE 1 2,047 11-06-2012, 17:50
Last Post: d0h!
  Post Your Real Life picture SniperGirl 87 40,516 10-22-2012, 23:21
Last Post: Arteq
  How to copy csharp source from a post? NooB_StalkeR 2 2,889 09-14-2012, 01:46
Last Post: NooB_StalkeR
  Post your YouTube videos AZUMIKKEL 6 4,109 09-03-2012, 11:55
Last Post: aosma8
  Your first post on this forum AZUMIKKEL 26 11,258 08-28-2012, 22:47
Last Post: Nekochan
  Post your favorite steam skins JariZ 55 39,408 08-26-2012, 11:46
Last Post: d0h!
  Post please new Server Offsets [Z00MBY] Alex 3 3,365 08-17-2012, 20:28
Last Post: JariZ
  Post your cosplay photos Lemon 11 12,138 04-07-2012, 02:33
Last Post: 4FunPlayin

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum Powered By MyBB, Theme by © 2002-2024 Melroy van den Berg.