网络请求

网络请求

一.原生网络请求Http’URLconnection

在安卓6.0系统中HTTP Client的功能被移除,标志着此功能被正式弃用,所有我们讲HttpURLconnection的用法。为网络请求是个耗时操作,所以肯定要用到线程。在写之前还是要在AndroidManifest中添加权限==uses-permission android:name=“android.permission.INTERNET”

HttpURLConnection常用的方法主要有两个:GET和POST,GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器。

  1. GET方法
 private void getHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("https://www.baidu.com/");
                    //得到connection对象。
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置请求方式
                    connection.setRequestMethod("GET");
                    //连接
                    connection.connect();
                    //得到响应码
                    int responseCode = connection.getResponseCode();
                    if(responseCode == HttpURLConnection.HTTP_OK){
                        //得到响应流
                        InputStream inputStream = connection.getInputStream();
                       System.out.println(responseCode);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuilder builder = new StringBuilder();
                        String line;
                        while((line = reader.readLine())!=null){
                            builder.append(line);
                        }
                        reader.close();
                        Log.i("wwwwwwwwww",builder.toString());
                        showResponse(builder.toString());
                    }
 
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private  void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mContent.setText(response);
            }
        });
    }

2.POST方法

// 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            //        params.setUseJsonStreamer(true);
            JSONObject body = new JSONObject();
            body.put("username", "panghao");
            body.put("password", "12345");
            String urlPath = "http://192.168.137.1:8080/login";
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            // 设置contentType
            conn.setRequestProperty("Content-Type", "application/json");
            DataOutputStream os = new DataOutputStream( conn.getOutputStream());
            String content = String.valueOf(body);
            os.writeBytes(content);
            os.flush();
            os.close();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
                BufferedReader bf = new BufferedReader(in);
                String recieveData = null;
                String result = "";
                while ((recieveData = bf.readLine()) != null){
                    result += recieveData + "\n";
                }
                in.close();
                conn.disconnect();
            }
        } catch (JSONException e) {
            throw e;
        } catch (IOException io){
            throw io;
        }

二.OkHttp网络请求

当然我们并不是只能使用HttpURLConnection,完全没有任何其他选择,事实上在开源盛行的今天,许多出色的网络通讯库都可以替代原生的HttPURLConnection,而且其中OkHTtp无疑是做的最出色的一个。

在使用OkHttp之前,我们需要先在项目中添加OkHttp库的依赖。编辑app/build.gradle文件,在dependencies闭包中添加如下内容:implementation 'com.squareup.okhttp3:okhttp:3.10.0’

  1. GET方法

String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
        .url(url)
        .get()//默认就是GET请求,可以不写
        .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d(TAG, "onFailure: ");
    }
 
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, "onResponse: " + response.body().string());
    }
});

2.POST方法


public class OkhttpUtils {
    public static  void  SendOkHttpRequest(String url,String username,String password,okhttp3.Callback callback){
        //创建一个OKHttpClient对象,官方推荐这个对象越少越好,就类似单例模式那样,复用这个对象
        OkHttpClient client = new OkHttpClient();
        
        //构造一个请求的内容
        RequestBody requestBody=new FormBody.Builder()
               .add("username",username)
               .add("password",password)
               .build();
        //准备发起一条http请求
        Request request = new Request.Builder()
                .url(url)
               .post(requestBody)
               .build();
        //发送请求,并把内容回调okhttp3.Callback中
        client.newCall(request).enqueue(callback);
      }
    }
//开启一个线程做数据提交
                      new Thread(new Runnable() {
                          @Override
                          public void run() {
                              OkhttpUtils.SendOkHttpRequest("url"
                                      ,userName,passWord,new okhttp3.Callback(){
                                          //异常的处理
                                          @Override
                                          public void onFailure(Call call, IOException e) {
                                              Log.d(TAG, e.getMessage());
                                          }
                                          //这里对返回的数据执行具体内容
                                          @Override
                                          public void onResponse(Call call, Response response) throws IOException {
                                              flag=response.body().string();
                                              Log.d(TAG,flag);
                                          
                                      });
                          }
                      }).start();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值