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

android网络通信之HttpUrlConnection

时间:2014-12-14 13:20:22      阅读:209      评论:0      收藏:0      [点我收藏+]

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

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

package com.liang.logindemo;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;


public class MainActivity 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(MainActivity.this,"成功!!!",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(MainActivity.this,"失败!!!",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * HttpUrlConnection通过GET请求方式访问服务器
     * @param userName,password
     * @return
     * @throws Exception
     */
    private Boolean loginByGet(String userName,String password) throws Exception{
        //服务器地址
        String url="http://192.168.1.58:8080/Login/servlet/Login";
        String data="?userName="+userName + "&password="+password;
        HttpURLConnection conn=null;
        InputStream is=null;
        BufferedReader reader=null;
        try {
            //定义一个URL
            URL murl=new URL(url+data);
            //打开连接获得HttpURLConnection
            conn = (HttpURLConnection) murl.openConnection();
            //设置请求方式
            conn.setRequestMethod("GET");
            //设置访问网络超时时间,超出时间会抛出异常
            conn.setConnectTimeout(5 * 1000);
            //设置读取超时时间
            conn.setReadTimeout(3 * 1000);
            //连接网络
            conn.connect();
            //获得返回的状态码
            int code = conn.getResponseCode();
            //200为正常响应
            if(code==200){
                //获得响应内容的输入流
                is = conn.getInputStream();
                //读取内容
                reader=new BufferedReader(new InputStreamReader(is));
                String state = reader.readLine();
                if("SUCCESS".equals(state)){
                    return true;
                }else{
                    return false;
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if(reader!=null){
                reader.close();
            }
            if(is!=null){
                is.close();
            }
            //关闭连接
            conn.disconnect();
        }
        return false;
    }

    /**
     *HttpUrlConnection通过POST请求方式访问服务器
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    boolean loginByPost(String userName,String password) throws Exception{
        String url="http://192.168.1.58:8080/Login/servlet/Login";
        HttpURLConnection conn=null;
        InputStream is=null;
        BufferedReader reader=null;
        OutputStream outputStream;
        String data="userName="+userName+"&password="+password;
        try {
            URL murl=new URL(url);
            conn = (HttpURLConnection) murl.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(3 * 1000);
            //设置允许打开输出流,默认为不打开
            conn.setDoOutput(true);
            //设置请求头信息,可设置多个
            //conn.setRequestProperty(key,value);

            //获得输出流,用于往服务器写入数据
            outputStream = conn.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
            conn.connect();
            int code = conn.getResponseCode();
            if(code==200){
                is = conn.getInputStream();
                reader=new BufferedReader(new InputStreamReader(is));
                String state = reader.readLine();
                if("SUCCESS".equals(state)){
                    return true;
                }else{
                    return false;
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if(reader!=null){
                reader.close();
            }
            if(is!=null){
                is.close();
            }
            conn.disconnect();
        }
        return false;

    }
}

布局两个输入框一个提交按钮,比较简单,就不列出了。

注意在清单文件中添加网络访问权限




android网络通信之HttpUrlConnection

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

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

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