`
龙哥IT
  • 浏览: 262377 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

androidasynchttp开源项目的GET或POST方式实现

 
阅读更多
android-async-http是一个强大的网络请求库,这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。
android-async-http是一个强大的第三方开源网络请求库,

官网源码:https://github.com/loopj/android-async-http

官网教程:http://loopj.com/android-async-http/


这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。

主要类介绍

AsyncHttpRequest

继承自Runnabler,被submit至线程池执行网络请求并发送start,success等消息


AsyncHttpResponseHandler

接收请求结果,一般重写onSuccess及onFailure接收请求成功或失败的消息,还有onStart,onFinish等消息


TextHttpResponseHandler

继承自AsyncHttpResponseHandler,只是重写了AsyncHttpResponseHandler的onSuccess和onFailure方法,将请求结果由byte数组转换为String


JsonHttpResponseHandler

继承自TextHttpResponseHandler,同样是重写onSuccess和onFailure方法,将请求结果由String转换为JSONObject或JSONArray


BaseJsonHttpResponseHandler

继承自TextHttpResponseHandler,是一个泛型类,提供了parseResponse方法,子类需要提供实现,将请求结果解析成需要的类型,子类可以灵活地使用解析方法,可以直接原始解析,使用gson等。


RequestParams

请求参数,可以添加普通的字符串参数,并可添加File,InputStream上传文件


AsyncHttpClient

核心类,使用HttpClient执行网络请求,提供了get,put,post,delete,head等请求方法,使用起来很简单,只需以url及RequestParams调用相应的方法即可,还可以选择性地传入Context,用于取消Content相关的请求,同时必须提供ResponseHandlerInterface(AsyncHttpResponseHandler继承自ResponseHandlerInterface)的实现类,一般为AsyncHttpResponseHandler的子类,AsyncHttpClient内部有一个线程池,当使用AsyncHttpClient执行网络请求时,最终都会调用sendRequest方法,在这个方法内部将请求参数封装成AsyncHttpRequest(继承自Runnable)交由内部的线程池执行。


SyncHttpClient

继承自AsyncHttpClient,同步执行网络请求,AsyncHttpClient把请求封装成AsyncHttpRequest后提交至线程池,SyncHttpClient把请求封装成AsyncHttpRequest后直接调用它的run方法。


服务器端php测试代码:

<?php
$data = array(
'status'=>'success', 
'get'=>json_encode($_GET), 
'post'=>json_encode($_POST),
'upload'=>json_encode($_FILES)
);
echo json_encode($data);

?>

android客户端测试代码:

package com.penngo.http;

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

public class HttpUtil {
    private static final String BASE_URL = "http://192.168.17.99/";

    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void setTimeout(){
        client.setTimeout(60000);
    }

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void download(String url, RequestParams params, FileAsyncHttpResponseHandler fileAsyncHttpResponseHandler){
        client.get(getAbsoluteUrl(url), params, fileAsyncHttpResponseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }
}
package com.penngo.http;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

public class MainActivity extends Activity {
    private final static String tag = "MainActivity-->";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button getBtn = (Button)this.findViewById(R.id.getBtn);
        getBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                testGet();
            }
        });
        Button postBtn = (Button)this.findViewById(R.id.postBtn);
        postBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                testPost();
            }
        });

        Button upLoadBtn = (Button)this.findViewById(R.id.upLoadBtn);
        upLoadBtn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                testUploadFile();
            }
        });

        Button downloadBtn = (Button)this.findViewById(R.id.downloadBtn);
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                testDownloadFile();
            }
        });
    }

    private void testGet(){
        HttpUtil.get("test/android.php", getParames(), responseHandler);
    }

    private RequestParams getParames(){
        RequestParams params = new RequestParams();
        params.put("user", "penngo");
        params.put("psw", "penngo");
        return params;
    }

    private TextHttpResponseHandler responseHandler =  new TextHttpResponseHandler(){
        @Override
        public void onStart() {
            Log.e(tag, "onStart====");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String response) {
            Log.e(tag, "onSuccess====");
            StringBuilder builder = new StringBuilder();
            for (Header h : headers) {
                String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
                builder.append(_h);
                builder.append("\n");
            }
            Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString() + " response:" + response);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable e) {
            Log.e(tag, "onFailure====");
            StringBuilder builder = new StringBuilder();
            for (Header h : headers) {
                String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
                builder.append(_h);
                builder.append("\n");
            }
            Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString(), e);
        }

        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
        }
    };

    private void testPost(){
        HttpUtil.post("test/android.php", getParames(), responseHandler);
    }

    private void testUploadFile(){
        RequestParams params = new RequestParams();
        try {
            InputStream is = this.getAssets().open("png/launcher.png");
            String png = this.getExternalCacheDir().getAbsolutePath() + "/launcher.png";
            File myFile = new File(png);
            Log.e(tag, "png====" + png);
            this.copyToSD(png, "png/launcher.png");
            params.put("pngFile", myFile, RequestParams.APPLICATION_OCTET_STREAM);
        } catch(Exception e) {
            Log.e(tag,"上传失败", e);
        }
        HttpUtil.post("test/android.php", params, responseHandler);
    }

    private void testDownloadFile(){
        String mp3 = this.getExternalCacheDir().getAbsolutePath() + "/fa.mp3";
        File mp3File = new File(mp3);
        FileAsyncHttpResponseHandler fileHandler = new FileAsyncHttpResponseHandler(mp3File){
            public void onSuccess(int statusCode, Header[] headers, File file){
                Log.e(tag, "onSuccess====");
                StringBuilder builder = new StringBuilder();
                for (Header h : headers) {
                    String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
                    builder.append(_h);
                    builder.append("\n");
                }
                Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString() + " file:" + file.getAbsolutePath());
            }
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file){

            }
        };
        HttpUtil.download("test/fa.mp3", null, fileHandler);
    }
    /**
     * 复制文件到sdcard
     */
    private void copyToSD(String strOut, String srcInput) throws IOException
    {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(strOut);
        myInput = this.getAssets().open(srcInput);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while(length > 0)
        {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }

        myOutput.flush();
        myInput.close();
        myOutput.close();
    }
}

 

分享到:
评论

相关推荐

    C++实现HTTP GET,POST请求

    本篇文章将详细探讨如何使用C++来实现HTTP GET和POST请求,以及涉及HTTPS的安全连接。 HTTP GET请求是HTTP协议中最基础的操作之一,主要用于从服务器获取资源。GET请求的所有参数都包含在URL中,因此它是透明且可...

    VC通过HttpGet和HttpPost方式与WebService通信,解析返回的Json

    可以使用开源的Json库,如jsoncpp或nlohmann/json,来帮助解析Json字符串。这些库提供了API,可以将Json字符串转换为C++对象,然后通过遍历这个对象,提取出所需的数据。 例如,假设Json响应如下: ```json { ...

    为知笔记开源项目程序源码,实现云笔记功能需要自己搭建服务器

    为知笔记开源项目程序源码,实现云笔记功能需要自己搭建服务器 为知笔记开源项目程序源码,实现云笔记功能需要自己搭建服务器 为知笔记开源项目程序源码,实现云笔记功能需要自己搭建服务器 为知笔记开源项目程序...

    c++封装curl,实现get,post,download

    本篇将深入探讨如何在C++中封装libcurl,实现GET、POST请求以及文件下载功能。 首先,我们从`curlpp`这个库开始。`curlpp`是libcurl的一个C++包装器,它提供了更方便、面向对象的API,简化了与libcurl的交互。要...

    开源项目-soheilhy-goget.zip

    综上所述,【开源项目-soheilhy-goget.zip】是一个致力于简化Go语言新手入门体验的项目,通过goget工具提供了一种便捷的环境安装方式。它涉及了Go语言环境的搭建、跨平台支持、源代码管理和开源社区协作等多个方面的...

    前端开源库-get-package-dir

    在前端开发领域,开源库是开发者们常用的工具,它们...在探索`get-package-dir-master`这个压缩包的内容时,我们可以查看源代码、示例和文档,以深入了解其内部实现和使用方式,从而更好地将其融入到自己的开发实践中。

    Java最著名的开源项目

    在Java的生态系统中,存在诸多著名的开源项目,这些项目各有特色,为Java开发人员提供了丰富的开发工具和应用架构。以下是对一些Java著名开源项目的详细介绍,它们分别在不同的开发领域中扮演着重要角色。 首先,...

    c#写的接口测试工具,支持post get put del请求

    2. 输入接口URL,选择请求类型(POST、GET、PUT或DELETE)。 3. 对于POST、PUT请求,可能需要填写请求体的数据,比如JSON格式的数据。 4. 设置额外的HTTP头,如Content-Type、Authorization等。 5. 发送请求并显示...

    Curl实现Get下载zip文件、post上传zip文件、普通post请求等

    本篇将详细介绍如何利用C++结合Curl库实现GET下载ZIP文件、POST上传ZIP文件以及普通POST请求以获取JSON数据。 首先,我们要理解GET和POST在网络请求中的基本概念。GET是HTTP协议中最常见的方法,用于请求服务器发送...

    AndroidAsyncHttp

    AndroidAsyncHttp是一个流行的开源库,专门用于在Android平台上进行异步网络请求。它由Loopj开发,旨在简化HTTP客户端操作,使开发者能够更方便地处理网络通信任务,而无需关心线程管理、回调处理等复杂细节。这个库...

    开源项目-carlmjohnson-get-headers.zip

    开源项目-carlmjohnson-get-headers.zip 是一个由开发者carlmjohnson创建的开源项目,主要功能是使用Go语言编写的一个简单工具,用于展示通过GET方法请求URL时返回的HTTP头信息。这个项目对于理解HTTP协议、学习Go...

    HttpClient发送http请求(post和get)需要的jar包+内符java代码案例+注解详解

    这个压缩包可能包含了实现HTTP GET和POST请求所需的jar包以及示例代码,帮助开发者理解如何使用HttpClient进行网络通信。下面将详细介绍HttpClient库,HTTP请求的基本概念,以及GET和POST方法的差异。 HttpClient是...

    用开源项目实现自定义switch

    "用开源项目实现自定义switch"这个主题,就是关于如何利用现有的开源资源来定制Android系统中的开关控件(Switch)。Switch是Android SDK中一个常用的ToggleButton,它提供了一种在两种状态之间切换的方式,通常用于...

    VC6.0实现POST和Get,调用后端WEBAPI接口_MFC版.rar

    HttpRequest.HttpPost("http://www.baidu.com/","",ret); ofstream OutFile("C:\\11111111111111.txt"); //利用构造函数创建txt文本,并且打开该文本 OutFile (); //把字符串内容,写入Test.txt文件 OutFile....

    视频通话 sipandroid 开源项目源码

    原来的网上的开源项目很多都跑不起来,这个项目,经本人修改,经测试在android4.0系统上运行已经没问题,研究了下,发现对需要做视频通话的人来讲还是有很大帮助,特此贡献出来,供大家研究学习,压缩文件是在linux...

    5个好玩的github游戏区开源项目

    在 IT 领域,开源项目一直扮演着重要的角色,它们不仅推动了技术的发展,也为开发者提供了学习和实践的平台。对于游戏爱好者来说,GitHub 上有许多有趣的开源游戏项目,能够让我们深入了解游戏开发的过程,甚至参与...

    GitHub开源项目SlidingMenu类库

    GitHub开源项目SlidingMenu的类库,导入之后可以直接使用 教程地址:http://blog.csdn.net/yangyu20121224/article/details/9255829

    pc远控android开源项目

    PC远程登录手机 登录之后,必然涉及到按键的模拟等操作。 三个开源的软件一个是SmartDog Studio的Remote Control Add-on 另一个是Webkey 最后一个是Android自带monkey

    FPGA优质开源项目获取方式

    内容包括各种FPGA优质开源项目的获取方式:1.FPGA优质开源模块 - SRIO、2.FPGA优质开源项目 - UDP RGMII千兆以太网、3.FPGA优质开源项目 - PCIE通信、4.FPGA优质开源项目 - DDR3读写、5.FPGA优质开源项目 - UDP万兆...

Global site tag (gtag.js) - Google Analytics