码迷,mamicode.com
首页 > 移动开发 > 详细

android通信HttpClient

时间:2014-12-14 13:19:32      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:android   blog   http   io   ar   os   使用   sp   for   

下面为使用HttpClient的一个登录服务器的小例子

package com.liang.logindemo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


public class MainActivity3 extends ActionBarActivity {
    private EditText et_userName;
    private EditText et_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_userName= (EditText) findViewById(R.id.et_userName);
        et_password= (EditText) findViewById(R.id.et_password);
    }

    public void login(View view) {
        String str=et_userName.getText().toString();
        try {
            str=URLEncoder.encode(str,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String userName=str;

        final String password=et_password.getText().toString();

        //在子线程中访问网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final boolean isSuccess =loginByPost(userName,password);
                    //final boolean isSuccess = loginByGet(userName,password);

                    //使用此方法可不使用Handler通知主线程,方法内所做操作由主线程完成
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(isSuccess){
                                Toast.makeText(MainActivity3.this,"成功了!!!",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(MainActivity3.this,"失败了!!!",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * HttpClient通过GET请求方式访问服务器
     * @param userName,password
     * @return
     * @throws Exception
     */
    private Boolean loginByGet(String userName,String password) throws Exception{
        //服务器地址
        String url="http://192.168.1.140:8080/Login/servlet/Login";
        String data="?userName="+userName + "&password="+password;
        HttpClient client=null;

        //定义一个客户端
        client = new DefaultHttpClient();
        //定义一个get请求
        HttpGet get = new HttpGet(url+data);
        //执行get请求,获得响应对象
        HttpResponse response = client.execute(get);
        //获得响应状态码
        int code = response.getStatusLine().getStatusCode();
        //返回结果
        if(code==200) {
            //获得响应内容
            InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String text = reader.readLine();
            reader.close();
            is.close();
            return "SUCCESS".equals(text) ? true : false;
        }
        if(client!=null){
            //关闭连接
            client.getConnectionManager().shutdown();
        }
        return false;
    }

    /**
     *HttpClient通过POST请求方式访问服务器
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    boolean loginByPost(String userName,String password) throws Exception{
        //服务器地址
        String url="http://192.168.1.140:8080/Login/servlet/Login";
        HttpClient client=null;

        //定义一个客户端
        client = new DefaultHttpClient();
        //定义一个Post请求
        HttpPost post = new HttpPost(url);
        //设置请求数据
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("userName",userName));
        list.add(new BasicNameValuePair("password",password));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
        post.setEntity(entity);
        //执行get请求,获得响应对象
        HttpResponse response = client.execute(post);
        //获得响应状态码
        int code = response.getStatusLine().getStatusCode();
        //返回结果
        if(code==200) {
            //获得响应内容
            InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String text = reader.readLine();
            reader.close();
            is.close();
            return "SUCCESS".equals(text) ? true : false;
        }
        if(client!=null){
            //关闭连接
            client.getConnectionManager().shutdown();
        }
        return false;

    }
}

需要清单文件中添加网络访问权限


android通信HttpClient

标签:android   blog   http   io   ar   os   使用   sp   for   

原文地址:http://blog.csdn.net/liang5630/article/details/41924363

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!