Android使用HTTP协议访问服务器

智能车锁的项目用户端的APP可以使用HTTP方式访问服务器,毕竟放在WEB容器中可能会稳定一点吧...

一、HTTP请求步骤

  1. 使用路径获取URL对象
  2. URL对象获取连接对象
  3. 连接对象设置超时时间、提交方式
  4. 查询状态码,若为200则访问成功
  5. 将服务器的返回的数据显示出来  

 

二、APP编程思路

  1. 放置两个按钮控件,分别用于GET和POST提交数据
  2. 初始化按钮控件,获取连接对象
  3. 设置点击事件
  4. 执行GET或POST连接
  5. ps:获取连接等耗时操作要在子线程中进行

 

三、代码

import android.os.Bundle;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    //声明控件
    Button getButton;
    Button postButton;
    
    //声明路径
    String Path;
    
    //声明连接对象
    URL url;
    HttpURLConnection getConnect;//get方式的连接对象
    HttpURLConnection postConnect;//post方式的连接对象
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();//初始化控件、连接
    }
    
    /**
     * 这是一个初始化控件、连接的方法
     */
    private void init(){
        getButton = (Button) findViewById(R.id.GET);
        postButton = (Button) findViewById(R.id.POST);
        getButton.setOnClickListener(this);
        postButton.setOnClickListener(this);
        
        Path = "https://www.baidu.com/";
        
        try {url = new URL(Path);} catch (Exception e) {System.out.println(e.getMessage());}
    }

    /**
     * 重写点击事件
     */
    @Override
    public void onClick(View v) {
        if(v.equals(getButton)){//get按钮点击
            get();
        }else if(v.equals(postButton)){//post方式点击
            post();
        }
    }
    
    /**
     * 这是一个get方式访问服务器的方法
     */
    private void get(){
        new Thread(new Runnable() {
            public void run() {
                try {
                    getConnect = (HttpURLConnection) url.openConnection();//获得连接对象
                    getConnect.setConnectTimeout(5000);//设置超时时间
                    getConnect.setRequestMethod("GET");//设置访问方式
                    //若要get方式传输数据,将path改为  Path = "https://www.baidu.com/?name=jingmo&age=18";
                    //判断响应码并获取返回信息
                    if(getConnect.getResponseCode()==200){
                        InputStream in = getConnect.getInputStream();
                        System.out.println(inputStream2String(in));
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }).start();
    }
    
    /**
     * 这是一个post方式访问服务器的方法
     */
    private void post(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    postConnect = (HttpURLConnection) url.openConnection();//获取连接对象
                    postConnect.setConnectTimeout(5000);//设置超时时间
                    postConnect.setRequestMethod("POST");//设置访问方式
                    //POST方式访问服务器传输数据是以流的方式传输的
                    postConnect.getOutputStream().write("我是数据".getBytes());
                    //判断响应码并获取返回信息
                    if(postConnect.getResponseCode()==200){
                        InputStream in = postConnect.getInputStream();
                        System.out.println(inputStream2String(in));
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }).start();
    }
    
    /**
     * 这是一个将输入流转为String类型的方法
     * @param in 输入流
     * @return 转换结果String
     */
    private String inputStream2String (InputStream in) throws IOException { 
        StringBuffer out = new StringBuffer(); 
        byte[] b = new byte[4096]; 
        for(int n;(n = in.read(b))!=-1;) { 
                out.append(new String(b, 0, n)); 
        } 
        return out.toString(); 
} 
    
}

小白一枚,有什么纰漏还请大神们指教。

 

posted @ 2017-12-14 21:28  sovagxa&静默  阅读(547)  评论(0编辑  收藏  举报