使用Apache HttpClient

package com.example.httpclienttest;

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

import org.apache.http.HttpEntity;
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.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 android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint(“NewApi”)
public class MainActivity extends Activity {

Button get;
Button login;
EditText response;
HttpClient httpClient;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
    // 创建DefaultHttpClient对象
    httpClient = new DefaultHttpClient();
    get = (Button) findViewById(R.id.get);
    login = (Button) findViewById(R.id.login);
    response = (EditText) findViewById(R.id.response);
    get.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // 创建一个HttpClient对象
            HttpGet get = new HttpGet("http://192.168.1.101:8080/WebTest/secret.jsp");
            // 发送GET请求
            try {
                HttpResponse httpResponse = httpClient.execute(get);
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    // 读取服务器响应
                    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        response.append(line + "\n");
                    }
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
            new AlertDialog.Builder(MainActivity.this).setTitle("登录系统").setView(loginDialog).setPositiveButton("login", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String name = ((EditText) loginDialog.findViewById(R.id.name)).getText().toString().trim();
                    String pass = ((EditText) loginDialog.findViewById(R.id.pass)).getText().toString().trim();
                    HttpPost post = new HttpPost("http://192.168.1.101:8080/WebTest/login.jsp");
                    // 如果传递参数个数比较多可以对传递的参数进行封装
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("name", name));
                    params.add(new BasicNameValuePair("pass", pass));
                    try {
                        // 设置请求参数
                        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());
                            Toast.makeText(getApplicationContext(), msg, 5000).show();
                        }
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).setNegativeButton("取消", null).show();

        }
    });
}

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

}

你可能感兴趣的:(使用Apache HttpClient)