web-dev-qa-db-ja.com

AndroidでHTTPPOSTを行う方法は?

私はAndroidアプリ開発に不慣れです、必要なのは2つのテキストボックスのユーザー名とパスワードを持っていることです。サーバーに投稿し、phpページを使用してDBで確認します。ログインが成功した場合次の画面に移動します。それ以外の場合は、ログインエラーを示すメッセージボックスを表示します。どうすればよいですか?

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://google.com");
    EditText tw =(EditText) findViewById(R.id.EditText01);
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        tw.setText(status);
    } catch (ClientProtocolException e) {
        tw.setText(e.toString());
    } catch (IOException e) {
        tw.setText(e.toString());
    }
} 
9
Alex Mathew

このクラスを使用します。

import Java.io.BufferedReader;
import Java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.OutputStreamWriter;
import Java.net.HttpURLConnection;
import Java.net.URL;

import Android.app.Activity;
import Android.os.Bundle;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.Toast;

public class HttpLogin extends Activity {
    /** Called when the activity is first created. */
    private Button login;
    private EditText username, password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        login = (Button) findViewById(R.id.login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String   mUsername = username.getText().toString();
                String  mPassword = password.getText().toString();

                tryLogin(mUsername, mPassword);
            }
        });
    }

    protected void tryLogin(String mUsername, String mPassword)
    {           
        HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;   
            String response = null;         
            String parameters = "username="+mUsername+"&password="+mPassword;   

            try
            {
                url = new URL("your login URL");
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();            
                String line = "";               
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                // Response from server after login process will be stored in response variable.                
                response = sb.toString();
                // You can perform UI operations here
                Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
                isr.close();
                reader.close();

            }
            catch(IOException e)
            {
                // Error
            }
    }
}

main.xmlは次のようになります。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:orientation="vertical"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
  >
<EditText Android:hint="Username" Android:id="@+id/username" Android:layout_width="fill_parent" Android:layout_height="wrap_content"></EditText>
<EditText Android:hint="Password" Android:id="@+id/password" Android:layout_width="fill_parent" Android:layout_height="wrap_content" Android:inputType="textPassword"></EditText>
<Button Android:text="Sign In" Android:id="@+id/login" Android:layout_width="fill_parent" Android:layout_height="wrap_content"></Button>
</LinearLayout>
33
Vikas Patidar

HttpClientを使用してPOSTリクエストを作成できます。例を参照してください ここ

1
kgiannakakis