发送Http请求

发送Http请求
1.HttpURLConnection
2.HttpCilent(API数量过多,扩展困难,不建议使用,6.0中已被移除)
3.OkHttp


  • HttpURLConnection
private void sendRequestWithHttpURLConnection(){
        //开启子线程来发起网络请求
        new Thread(new Runnable(){
            @Override
            public void run(){
                HttpURLConnection connection=null;
                BufferedReader reader=null;
                try{
                    //获取HttpURLConnection实例
                    URL url=new URL("https://www.baidu.com");
                    connection=(HttpURLConnection)url.openConnection();
                    //设置HTTP请求使用的方法
                    connection.setRequestMethod("GET");
                    //其他设置
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    //获取服务器返回的输入流
                    InputStream in=connection.getInputStream();

                    //读取获取到的输入流
                    reader=new BufferedReader(new InputStreamReader(in));
                    StringBuilder response=new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null){
                        response.append(line);
                    }
                    showResponse(response.toString());

                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    if(reader!=null){
                        try{
                            reader.close();
                        }catch(IOException e){
                            e.printStackTrace();
                        }
                    }
                    if(connection!=null){
                        //关闭HTTP连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

网络请求是很耗时的操作,所以要开启子线程
首先要获取HttpURLConnection实例,采用URL.openConnection()方法
设置Http请求所使用的方法,GET(从服务器获取数据),POST(向服务器提交数据)
还可设置链接超时,读取超时毫秒数以及服务器希望得到的一下消息头等
HttpURLConnection.getInputStream()方法获取服务器返回的InputStream输入流
对输入流进行读取,最后关闭HTTP连接使用HttpURLConnection.disconnect()方法

//Android不允许在子线程中进行UI操作,要用runOnUiThread方法切换到主线程
    private  void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作
                mTextViewResponseText.setText(response);
            }
        });
    }

发送信息给服务器
把请求方法改成POST并在获取输入流之前把要提交的数据写出

connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

注意每条数据都以键值对的形式存在,数据与数据之间用&隔开


  • OkHttp
private void sendRequestWithOkHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //创建OkHttpClient实例
                    OkHttpClient client=new OkHttpClient();
                    //Requst是OkHttp库里的
                    //builder之前可连缀的方法还有很多
                    //10.0.2.2对于模拟器来说就是电脑本机的IP地址
                    Request request=new Request.Builder()
                            .url("http://10.0.2.2/get_data.json")
                            .build();
                    //创建call对象,并调用它的execute方法来发送请求并获取服务器返回的数据
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    //parseXMLWithPull(responseData);
                    //parserXMLWithSAX(responseData);
                    //parseJSONWithJSONObject(responseData);
                    parserJSONWithGSON(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

创建OkHttpClient实例
创建Request实例,并在此时传入url
利用OkHttpClient.newCall()方法传入Request对象来创建call对象
调用call对象的execute()方法来发送请求并获取服务器返回的数据Response对象
调用Response.body().string可将返回的数据转换成string,在把它送去解析


发送信息给服务器
构建RequestBody对象用来存放待提交的参数

RequestBody requestBody=new FormBody.Builder()
                .add("username","admin")
                .add("password","123456")
                .build();

调用Request.Builder中的post()方法传入RequestBody对象

Request request=new Request.Builder()
          .url("http://www.baidu.com")
          .post(requestBody)
          .builder();

你可能感兴趣的:(发送Http请求)