当前位置: 移动技术网 > IT编程>开发语言>Java > Java调用Http接口(5)--HttpAsyncClient调用Http接口

Java调用Http接口(5)--HttpAsyncClient调用Http接口

2019年11月27日  | 移动技术网IT编程  | 我要评论
HttpAsyncClient是HttpClient的异步版本,提供异步调用的api。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.1.4。 1、服务端 参见Java调用Http接口(1)--编写服务端 2、调用 2.1、GET请求 public static vo ...

httpasyncclient是httpclient的异步版本,提供异步调用的api。文中所使用到的软件版本:java 1.8.0_191、httpclient 4.1.4。

1、服务端

参见java调用http接口(1)--编写服务端 

2、调用

2.1、get请求

    public static void get() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/getuser?userid=1000&username=" + urlencoder.encode("李白", "utf-8");
            httpget get = new httpget(requestpath);
            future<httpresponse> future = httpclient.execute(get, null);
            httpresponse response = future.get();
            system.out.println("get返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("get返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式调用
            final countdownlatch latch = new countdownlatch(1);
            final httpget get2 = new httpget(requestpath);
            httpclient.execute(get2, new futurecallback<httpresponse>() {
                public void completed(final httpresponse response) {
                    latch.countdown();
                    system.out.println("get(回调方式)返回状态:" + response.getstatusline());
                    try {
                        system.out.println("get(回调方式)返回结果:" + entityutils.tostring(response.getentity()));
                    } catch (exception e) {
                        e.printstacktrace();
                    }
                }
                public void failed(final exception e) {
                    latch.countdown();
                    e.printstacktrace();
                }
                public void cancelled() {
                    latch.countdown();
                    system.out.println("cancelled");
                }

            });
            latch.await();
            
            //流方式调用
            final countdownlatch latch2 = new countdownlatch(1);
            final httpget get3 = new httpget(requestpath);
            httpasyncrequestproducer producer3 = httpasyncmethods.create(get3);
            asyncbyteconsumer<httpresponse> consumer3 = new asyncbyteconsumer<httpresponse>() {
                httpresponse response;
                @override
                protected void onresponsereceived(final httpresponse response) {
                    this.response = response;
                }
                @override
                protected void releaseresources() {
                }
                @override
                protected httpresponse buildresult(final httpcontext context) {
                    return this.response;
                }
                @override
                protected void onbytereceived(bytebuffer buf, iocontrol ioctrl) throws ioexception {
                    system.out.println("get(流方式)返回结果:" + new string(buf.array()));
                }
            };
            httpclient.execute(producer3, consumer3, new futurecallback<httpresponse>() {
                public void completed(final httpresponse response) {
                    latch2.countdown();
                    system.out.println("get(流方式)返回状态:" + response.getstatusline());
                }
                public void failed(final exception e) {
                    latch2.countdown();
                    e.printstacktrace();
                }
                public void cancelled() {
                    latch2.countdown();
                    system.out.println("cancelled");
                }
            });
            latch2.await();
            
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }

2.2、post请求(发送键值对数据)

    public static void post() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/getuser";
            httppost post = new httppost(requestpath);
            
            list<namevaluepair> list = new arraylist<namevaluepair>();
            list.add(new basicnamevaluepair("userid", "1000"));
            list.add(new basicnamevaluepair("username", "李白"));
            post.setentity(new urlencodedformentity(list, "utf-8"));
            
            future<httpresponse> future = httpclient.execute(post, null);
            httpresponse response = future.get();
            system.out.println("post返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("post返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式和流方式调用类似
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }

2.3、post请求(发送json数据)

    public static void post2() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/adduser";
            httppost post = new httppost(requestpath);
            post.setheader("content-type", "application/json");
            string param = "{\"userid\": \"1001\",\"username\":\"杜甫\"}";
            post.setentity(new stringentity(param, "utf-8"));
            
            future<httpresponse> future = httpclient.execute(post, null);
            httpresponse response = future.get();
            system.out.println("post json返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("post josn返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式和流方式调用类似
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }

2.4、上传文件

    public static void upload() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/upload";
            zerocopypost producer = new zerocopypost(requestpath, new file("d:/a.jpg"), contenttype.create("text/plain"));
            asyncbyteconsumer<httpresponse> consumer = new asyncbyteconsumer<httpresponse>() {
                httpresponse response;
                @override
                protected void onresponsereceived(final httpresponse response) {
                    this.response = response;
                }
                @override
                protected void releaseresources() {
                }
                @override
                protected httpresponse buildresult(final httpcontext context) {
                    return this.response;
                }
                @override
                protected void onbytereceived(bytebuffer buf, iocontrol ioctrl) throws ioexception {
                    system.out.println("upload返回结果:" + new string(buf.array()));
                }
            };
            future<httpresponse> future = httpclient.execute(producer, consumer, null);
            httpresponse response = future.get();
            system.out.println("upload返回状态:" + response.getstatusline());
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }

2.5、下载文件

    public static void download() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/download";
            httpget get = new httpget(requestpath);
            httpasyncrequestproducer producer = httpasyncmethods.create(get);
            file download = new file("d:/temp/download_" + system.currenttimemillis() + ".jpg");
            zerocopyconsumer<file> consumer = new zerocopyconsumer<file>(download) {
                @override
                protected file process(final httpresponse response, final file file, final contenttype contenttype) throws exception {
                    if (response.getstatusline().getstatuscode() != httpstatus.sc_ok) {
                        throw new clientprotocolexception("upload failed: " + response.getstatusline());
                    }
                    return file;
                }
            };
            future<file> future = httpclient.execute(producer, consumer, null);
            system.out.println("download文件大小:" + future.get().length());
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }

2.6、完整例子

package com.inspur.demo.http.client;

import java.io.file;
import java.io.ioexception;
import java.net.urlencoder;
import java.nio.bytebuffer;
import java.util.arraylist;
import java.util.list;
import java.util.concurrent.countdownlatch;
import java.util.concurrent.future;

import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.namevaluepair;
import org.apache.http.client.clientprotocolexception;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.concurrent.futurecallback;
import org.apache.http.entity.contenttype;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.nio.client.closeablehttpasyncclient;
import org.apache.http.impl.nio.client.httpasyncclients;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.nio.iocontrol;
import org.apache.http.nio.client.methods.asyncbyteconsumer;
import org.apache.http.nio.client.methods.httpasyncmethods;
import org.apache.http.nio.client.methods.zerocopyconsumer;
import org.apache.http.nio.client.methods.zerocopypost;
import org.apache.http.nio.protocol.httpasyncrequestproducer;
import org.apache.http.protocol.httpcontext;
import org.apache.http.util.entityutils;

/**
 * 通过httpclient调用http接口
 *
 */
public class httpasyncclientcase {
    /**
     *  get请求
     */
    public static void get() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/getuser?userid=1000&username=" + urlencoder.encode("李白", "utf-8");
            httpget get = new httpget(requestpath);
            future<httpresponse> future = httpclient.execute(get, null);
            httpresponse response = future.get();
            system.out.println("get返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("get返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式调用
            final countdownlatch latch = new countdownlatch(1);
            final httpget get2 = new httpget(requestpath);
            httpclient.execute(get2, new futurecallback<httpresponse>() {
                public void completed(final httpresponse response) {
                    latch.countdown();
                    system.out.println("get(回调方式)返回状态:" + response.getstatusline());
                    try {
                        system.out.println("get(回调方式)返回结果:" + entityutils.tostring(response.getentity()));
                    } catch (exception e) {
                        e.printstacktrace();
                    }
                }
                public void failed(final exception e) {
                    latch.countdown();
                    e.printstacktrace();
                }
                public void cancelled() {
                    latch.countdown();
                    system.out.println("cancelled");
                }

            });
            latch.await();
            
            //流方式调用
            final countdownlatch latch2 = new countdownlatch(1);
            final httpget get3 = new httpget(requestpath);
            httpasyncrequestproducer producer3 = httpasyncmethods.create(get3);
            asyncbyteconsumer<httpresponse> consumer3 = new asyncbyteconsumer<httpresponse>() {
                httpresponse response;
                @override
                protected void onresponsereceived(final httpresponse response) {
                    this.response = response;
                }
                @override
                protected void releaseresources() {
                }
                @override
                protected httpresponse buildresult(final httpcontext context) {
                    return this.response;
                }
                @override
                protected void onbytereceived(bytebuffer buf, iocontrol ioctrl) throws ioexception {
                    system.out.println("get(流方式)返回结果:" + new string(buf.array()));
                }
            };
            httpclient.execute(producer3, consumer3, new futurecallback<httpresponse>() {
                public void completed(final httpresponse response) {
                    latch2.countdown();
                    system.out.println("get(流方式)返回状态:" + response.getstatusline());
                }
                public void failed(final exception e) {
                    latch2.countdown();
                    e.printstacktrace();
                }
                public void cancelled() {
                    latch2.countdown();
                    system.out.println("cancelled");
                }
            });
            latch2.await();
            
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }
    
    /**
     *  post请求(发送键值对数据)
     */
    public static void post() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/getuser";
            httppost post = new httppost(requestpath);
            
            list<namevaluepair> list = new arraylist<namevaluepair>();
            list.add(new basicnamevaluepair("userid", "1000"));
            list.add(new basicnamevaluepair("username", "李白"));
            post.setentity(new urlencodedformentity(list, "utf-8"));
            
            future<httpresponse> future = httpclient.execute(post, null);
            httpresponse response = future.get();
            system.out.println("post返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("post返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式和流方式调用类似
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }
    
    /**
     *  post请求(发送json数据)
     */
    public static void post2() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/adduser";
            httppost post = new httppost(requestpath);
            post.setheader("content-type", "application/json");
            string param = "{\"userid\": \"1001\",\"username\":\"杜甫\"}";
            post.setentity(new stringentity(param, "utf-8"));
            
            future<httpresponse> future = httpclient.execute(post, null);
            httpresponse response = future.get();
            system.out.println("post json返回状态:" + response.getstatusline());
            httpentity responseentity = response.getentity();
            system.out.println("post josn返回结果:" + entityutils.tostring(responseentity));
            
            //回调方式和流方式调用类似
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }
    
    /**
     * 上传文件
     */
    public static void upload() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/upload";
            zerocopypost producer = new zerocopypost(requestpath, new file("d:/a.jpg"), contenttype.create("text/plain"));
            asyncbyteconsumer<httpresponse> consumer = new asyncbyteconsumer<httpresponse>() {
                httpresponse response;
                @override
                protected void onresponsereceived(final httpresponse response) {
                    this.response = response;
                }
                @override
                protected void releaseresources() {
                }
                @override
                protected httpresponse buildresult(final httpcontext context) {
                    return this.response;
                }
                @override
                protected void onbytereceived(bytebuffer buf, iocontrol ioctrl) throws ioexception {
                    system.out.println("upload返回结果:" + new string(buf.array()));
                }
            };
            future<httpresponse> future = httpclient.execute(producer, consumer, null);
            httpresponse response = future.get();
            system.out.println("upload返回状态:" + response.getstatusline());
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }
    
    /**
     * 下载文件
     */
    public static void download() {
        closeablehttpasyncclient httpclient = httpasyncclients.createdefault();
        try {
            httpclient.start();
            string requestpath = "http://localhost:8080/demo/httptest/download";
            httpget get = new httpget(requestpath);
            httpasyncrequestproducer producer = httpasyncmethods.create(get);
            file download = new file("d:/temp/download_" + system.currenttimemillis() + ".jpg");
            zerocopyconsumer<file> consumer = new zerocopyconsumer<file>(download) {
                @override
                protected file process(final httpresponse response, final file file, final contenttype contenttype) throws exception {
                    if (response.getstatusline().getstatuscode() != httpstatus.sc_ok) {
                        throw new clientprotocolexception("upload failed: " + response.getstatusline());
                    }
                    return file;
                }
            };
            future<file> future = httpclient.execute(producer, consumer, null);
            system.out.println("download文件大小:" + future.get().length());
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            try {httpclient.close();} catch (ioexception e) {e.printstacktrace();}
        }
    }
    
    public static void main(string[] args) {
        get();
        post();
        post2();
        upload();
        download();
    }
}

 

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网