当前位置: 移动技术网 > 移动技术>移动开发>Android > Android Http协议访问网络实例(3种)

Android Http协议访问网络实例(3种)

2019年07月24日  | 移动技术网移动技术  | 我要评论

之前关于android http协议访问网络的一点分析,最近需要回顾,就顺便发到随笔上了

android中http连接主要是为了获取网络数据,目前了解的有3种方法:

  1. httpconnection ——本人常用
  2. okhttp——看见过(需要在依赖中引入包)
  3. httpclient——过气的方法(弃用)

httpconnection

由于网络连接是耗时操作不能在ui线程操作,一般通过handler获取子线程中获取的数据

handler mhandler=new handler(){
    @override
    public void handlemessage(message msg) {
      super.handlemessage(msg);
      //数据处理逻辑
    }
  };

如何在ui线程中调用http方法类(很久以前琢磨了很久):

new jsontext(mhandler);

返回的类型都是string,这里直接写在一个类里以后方便用

public class jsontest {
  handler handler;
  public jsontest(handler handler) {
    this.handler = handler;
    thread.start();
  }

  thread thread=new thread(new runnable() {
    @override
    public void run() {
      message msg=new message();
      try{
        inputstream in=null;
        httpurlconnection connection=null;
        url url=new url("http://guolin.tech/api/china");
        connection=(httpurlconnection)url.openconnection();
        connection.setrequestmethod("get");//设置请求方式,可以不设置,默认是get
        connection.setconnecttimeout(5000);//设置请求超时时间
        in=connection.getinputstream();
        msg.arg1=0x01;
        msg.obj=in.tostring();
        handler.sendmessage(msg);
      }catch (exception e){
        e.printstacktrace();
        msg.arg1=0x02;
        handler.sendmessage(msg);
      }finally {
        connection.disconnect();
      }
    }
  });
}

代码不复杂就不赘述了,接下来说其他几点:

thread:

经常听到有问sleep()和wait()有什么区别。sleep()方法来自thread类中,而wait()来自object类中;其次,sleep()方法调用的时候不出让系统资源,wait()让出系统资源其他线程可以占用cpu;最后,sleep(milliseconds)需要指定一个睡眠时间,时间一到会自动唤醒。

http(超文本传输协议) ,https(超文本传输协议安全版)

关于tcp/ip 和upd:

tcp/ip比udp稳定,但是慢,因为它有三次握手机制

关于三次握手:

网上有很多解释,自己叙述就是主机先问服务器,我可以发数据了吗,服务器回答,可以了,主机在说,那我发了。具体的内容以后在详细理解,先上图


okhttp

书上的描述是:出色的网络通信库可以用来代替httpconnection。你说出色我就用咯。

添加依赖:

dependencies {
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

使用

okhttpclient client =new okhttpclient();
//创建实例
request request =new request.builder().build();

通过url()访问网络:

request request =new request.builder().url("www.baidu.com").build();

之后调用newcall()方法创建call对象,并调用excute()方法发送请求并获取服务器数据:

response response=client.newcall(request).excute();
string str=response..body().tostring();//得到值

说一下上述两个方法都只说了get,没有post(提交数据),原因是懒了,以后再说

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网