http异步请求

Posted zhongyinghe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了http异步请求相关的知识,希望对你有一定的参考价值。

1、加载异步请求包文件

2、java代码

package com.example.asynchttp;

import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view){
        AsyncHttpClient client = new AsyncHttpClient();

        String path = "http://192.168.1.100/android/add.php";
        client.get(path, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                    byte[] responseBody) {
                // TODO Auto-generated method stub
                String result = new String(responseBody);
                Toast.makeText(MainActivity.this, result, 0).show();
                
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "失败!", 0).show();
                
            }
          
            
        });
    }
    
    public void click2(View view){
        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://192.168.0.86/android/add.php";
        
        RequestParams params = new RequestParams();
        params.put("username", "zhangsan");
        params.put("password", "123456");
        client.post(url, params, new AsyncHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                    byte[] responseBody) {
                // TODO Auto-generated method stub
                String result = new String(responseBody);
                Toast.makeText(MainActivity.this, result, 0).show();
                
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "请求失败!", 0).show();
                
            }
            
        });
    }
    
}

 

以上是关于http异步请求的主要内容,如果未能解决你的问题,请参考以下文章

jQuery-异步请求

简单的 Javascript http 请求片段但不起作用

http异步请求

我应该在 Fragment 中的啥生命周期状态下执行异步任务?

原创-算法-实现异步HTTP请求操作

求教golang中http发送post请求gb2312编码的解决方案