android登录post方法

时间:2011-11-15 18:58:53

标签: android post login

嗨我开始使用android开发,我必须创建一个点击按钮的登录表单,它会发送:http://www.mypage.com/?U=USUARI&K=PASSWORD。 在这里搜索我已经创建了一个Vikas Patidar上传的方法,我试图根据我的需要修改它。但我觉得有些不对劲,因为它不起作用。 你能告诉我在哪里错了吗?

这是代码 `

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

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

    login = (Button) findViewById(R.id.login);
    U = (EditText) findViewById(R.id.U);
    K = (EditText) findViewById(R.id.K);

    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String   mUsername = U.getText().toString();
            String  mPassword = K.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 = "U="+mUsername+"&K="+mPassword;   

        try
        {
            url = new URL("http://http://www.mypage.com/content/frmLogin.aspx");
            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
        }
}
´

,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/U" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</EditText>

<EditText 
android:hint="Password" 
android:id="@+id/K" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:inputType="textPassword">
</EditText>

<Button 
android:text="Iniciar Sessió" 
android:id="@+id/login" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
</LinearLayout>

现在我正在尝试使用HTTP GET方法,我得到了这个

packge com.android.v3;

import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

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.TextView;

public class v3act extends Activity {
    TextView Tname,Tpass;
    EditText Ename,Epass;
    Button btnCreate;
     String n=null;
     String contentOfMyInputStream1;
     String output = null;


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

        btnCreate = (Button) findViewById(R.id.btnGen);
        Tname = (TextView) findViewById(R.id.txtName);
        Ename = (EditText) findViewById(R.id.editName);
        Tpass = (TextView) findViewById(R.id.txtPass);
        Epass = (EditText) findViewById(R.id.editPass);




        btnCreate.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            Tname.setText("");
            // Thread thread = new Thread();
             String st1;

             st1=Ename.getText().toString();
            //thread.start();

             Tpass.setText("");
             // Thread thread = new Thread();
              String st2;

              st2=Epass.getText().toString();
             //thread.start();

            try {
                 output ="http://www.mypage.com/?U="+st1+"K="+st2;
                downloadUrl(output);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (output != null) 
            {
                Tname.setText(output);
            }


            }
            });


    }

    public String downloadUrl(String url) throws  IOException{
        HttpClient httpclient = new DefaultHttpClient();  
        HttpRequestBase httpRequest = null;
        HttpResponse httpResponse = null;
        InputStream inputStream = null;
        String response = "";
        StringBuffer buffer = new StringBuffer();

        httpRequest = new HttpGet(url); 

        httpResponse = httpclient.execute(httpRequest);
        inputStream = httpResponse.getEntity().getContent();
        int contentLength = (int) httpResponse.getEntity().getContentLength();
        if (contentLength < 0){
           // Log.e(TAG, "The HTTP response is too long.");
        }
        byte[] data = "8" byte[256];
        int len = 0;
        while (-1 != (len = inputStream.read(data)) )
        {
            buffer.append(new String(data, 0, len));
        }

        inputStream.close();

        response = buffer.toString();

        return response;

    }


}

但我在这行上有一些错误:

byte[] data = "8" byte[256];

它说:'令牌上的语法错误“byte”,删除此令牌' 如果我删除它,我会在反应中得到更多错误。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

删除

The conn.setRequestMethod("POST");

然后conn.setDoOutput(true);已经意味着您正在使用POST通信。

下。

        request.write(parameters);
        request.flush();
        request.close();

将其更改为

        request.write(parameters.getBytes());
        request.flush();
        //request.close();//it is closing prematurly so you will definitely not get any response at all... 

尝试这些并让我知道它是否结果好啊......

如果您想查看看起来与您的情况几乎相似的this example ...

可能会帮助太多......回应。