Android Apache HttpClient

来源:互联网 发布:linux tgz 编辑:程序博客网 时间:2024/06/05 08:17

这里写图片描述

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="shortcut.song.com.myapplication.HttpClientActivity">    <TextView        android:id="@+id/http_response"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="..........."/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="showLogin"        android:text="Login"/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="accessSecret"        android:text="Secret"/></LinearLayout>

login.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="name"/>        <EditText            android:id="@+id/login_name"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="input name"/>    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="passowd"/>        <EditText            android:id="@+id/login_pws"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="input password"/>    </LinearLayout></LinearLayout>
package shortcut.song.com.myapplication;import android.content.DialogInterface;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public class HttpClientActivity extends AppCompatActivity {    TextView response;    HttpClient httpClient;    private Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg.what == 0x1234) {                // 将服务器响应内容显示到文本框                response.setText(msg.obj.toString() +"\n");            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_http_client);        // 创建 DefaultHttpClient对象        httpClient = new DefaultHttpClient();        response = (TextView)findViewById(R.id.http_response);    }    public void accessSecret(View v) {        response.setText("");        new Thread(){            @Override            public void run() {                super.run();                // 创建一个HttpGet对象                HttpGet httpGet = new HttpGet("http://192.168.8.27/index.html");                try {                    HttpResponse httpResponse = httpClient.execute(httpGet);                    HttpEntity entity = httpResponse.getEntity();                    if (entity != null){                        // 读取服务器响应);                        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));                        String line = null;                        while((line = br.readLine()) != null) {                            Message msg = new Message();                            msg.what = 0x1234;                            msg.obj = line;                            mHandler.sendMessage(msg);                        }                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        }.start();    }    public void showLogin(View v){        // 加载登录界面        final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);        // 使用对话框供用户登录系统        new AlertDialog.Builder(HttpClientActivity.this)                .setTitle("Login")                .setView(loginDialog)                .setPositiveButton("Loging --", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        // 获取用户输入的,用户,密码                        final String userName = ((EditText)findViewById(R.id.login_name)).getText().toString();                        final String userPassword = ((EditText)findViewById(R.id.login_pws)).getText().toString();                        new Thread() {                            @Override                            public void run() {                                try{                                    HttpPost post = new HttpPost("http://192.168.8.27/index.html");                                    // 如果传递的参数比较多,可以对传递的参做进行封装                                    List<NameValuePair> params = new ArrayList<NameValuePair>();                                    params.add(new BasicNameValuePair("name", userName));                                    params.add(new BasicNameValuePair("pass", userPassword));                                    // 设置请求参数                                    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));                                    // 发送POST 请求                                    HttpResponse response = httpClient.execute(post);                                    // 如果服务器成功返回                                    if (response.getStatusLine().getStatusCode() == 200 ) {                                        String msg = EntityUtils.toString(response.getEntity());                                        Looper.prepare();                                        // 提示成功登录                                        Toast.makeText(HttpClientActivity.this, msg, Toast.LENGTH_SHORT).show();                                        Looper.loop();                                    }                                } catch (IOException e) {                                    e.printStackTrace();                                }                            }                        }.start();                    }                })                .setNegativeButton("Cancel", null)                .show();    }}