如何在 Android 中执行 HTTP Post? [英] How to do a HTTP Post in Android?

查看:36
本文介绍了如何在 Android 中执行 HTTP Post?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 应用程序开发的新手,我需要的是我有两个文本框用户名和密码,它将发布到服务器并使用 php 页面与数据库进行检查,如果登录成功,则转到下一个屏幕,否则显示显示登录错误的消息框我该怎么做?

i am new to android app development, what i need is i have two textbox username and password,it will post to server and check it with the DB using a php page, if the login success then go to next screen else show a msg box showing login error how can i do that?

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());
    }
} 

推荐答案

使用这个类:

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 + "
");
                }
                // 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: 
"+ response, 0).show();             
                isr.close();
                reader.close();

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

main.xml 将是这样的:

main.xml will be like this:

<?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>

这篇关于如何在 Android 中执行 HTTP Post?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆