Andriod开源框架asynchttpclient基本使用

Andriod开源框架asynchttpclient基本使用

    • 1.导入相关依赖
    • 2.代码实现
      • 2.1使用get方式来发送请求
      • 2.2使用post请求方式发送请求

1.导入相关依赖

在build.gradle中dependencies中添加
implementation ‘net.callumtaylor:asynchttpclient:2.1.1’

2.代码实现

2.1使用get方式来发送请求

/**
     * 使用get请求方式来向服务器发送数据
     * @param view
     */
    public void getToLogin(View view)
    {
        //发送请求url
        path = "http://192.168.6.57:8080/login?username=" + etUserName.getText().toString().trim() + "&userpass=" + etUserPass.getText().toString().trim();

        //初始化一个asynchttpclient对象,传入请求的url
        AsyncHttpClient httpClient = new AsyncHttpClient(path);

        //使用get请求,响应处理器使用jsonresponsehandler,还有其他响应处理器
        httpClient.get(new JsonResponseHandler()
               {
                   //请求成功时候执行的代码
                   @Override
                   public void onSuccess()
                   {
                       JsonElement element = getContent();
                       final String asString = element.getAsString();
                       runOnUiThread(new Runnable()
                       {
                           @Override
                           public void run()
                           {
                               Toast.makeText(getApplicationContext(), asString, Toast.LENGTH_LONG).show();
                           }
                       });
                   }
                   
                   //请求失败的时候执行的代码
                   @Override
                   public void onFailure()
                   {
                       JsonElement element = getContent();
                       String asString = element.getAsString();
                       Toast.makeText(getApplicationContext(), asString, Toast.LENGTH_LONG).show();
                   }
               }
        );

    }

2.2使用post请求方式发送请求

public void postToLogin(View view)
    {
        path = "http://192.168.6.57:8080";
        String username = etUserName.getText().toString().trim();
        String userpass = etUserPass.getText().toString().trim();


        AsyncHttpClient httpClient = new AsyncHttpClient(path);
        
        //post请求的data数据,键值对的列表
        List<NameValuePair> params = new ArrayList<>();
        params.add(new NameValuePair("username", username));
        params.add(new NameValuePair("userpass", userpass));


        //这边是uri路径,全称为http://192.168.6.57:8080/login,上面已经传入了服务器路径,这边只要写子目录
        httpClient.post("login", params, new StringResponseHandler()
        {
            @Override
            public void onSuccess()
            {
                final String asString = getContent();
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast.makeText(getApplicationContext(), asString, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

你可能感兴趣的:(Andriod)