欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HttpClient 远程接口调用方式

程序员文章站 2023-02-07 14:51:37
远程接口调用方式HttpClient 问题:现在我们已经开发好了接口了,那该如何调用这个接口呢? 答:使用Httpclient客户端。 Httpclient简介 什么是httpclient HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能 ......
远程接口调用方式httpclient
问题:现在我们已经开发好了接口了,那该如何调用这个接口呢?
答:使用httpclient客户端。
 
httpclient简介
什么是httpclient
httpclient apache jakarta common 下的子项目,用来提供高效的、最新的、功能丰富的支持 http 协议的客户端编程工具包,并且它支持 http 协议最新的版本和建议。实现了所有 http 的方法(get,post,put,head 等)
下载地址:http://hc.apache.org/
 
httpclient作用
java代码中,发送http请求。通常用来实现远程接口调用。
httpclient测试
在工程中添加httpclientpom依赖。
<dependency>
    <groupid>org.apache.httpcomponents</groupid>
    <artifactid>httpclient</artifactid>
</dependency>

 

执行get请求
public static void doget(){
 // 创建httpclient对象
        closeablehttpclient httpclient = httpclients.createdefault();
 
        // 创建http get请求
        httpget httpget = new httpget("http://www.oschina.net/");
 
        closeablehttpresponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpget);
            system.out.println(response.getstatusline());
            // 判断返回状态是否为200
            if (response.getstatusline().getstatuscode() == 200) {
                string content = entityutils.tostring(response.getentity(), "utf-8");
                system.out.println("内容长度:" + content.length());
            }
        }catch(exception e){
         e.printstacktrace();
        
        } finally {
            if (response != null) {
                try {
response.close();
} catch (ioexception e) {
e.printstacktrace();
}
            }
            try {
httpclient.close();
} catch (ioexception e) {
e.printstacktrace();
}
        }

 

 
执行get带参数
public static void dogetparam(){
 // 创建httpclient对象
closeablehttpclient httpclient = httpclients.createdefault();
closeablehttpresponse response = null;
try {
 
        // 定义请求的参数
        uri uri = new uribuilder("http://www.baidu.com/s").setparameter("wd", "数据库").build();
 
        system.out.println(uri);
 
        // 创建http get请求
        httpget httpget = new httpget(uri);
 
            // 执行请求
            response = httpclient.execute(httpget);
            // 判断返回状态是否为200
            if (response.getstatusline().getstatuscode() == 200) {
                string content = entityutils.tostring(response.getentity(), "utf-8");
                system.out.println(content);
            }
        }catch(exception e){
         e.printstacktrace();
        
        }finally {
            if (response != null) {
                try {
response.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
            }
            try {
httpclient.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
        }
}

 

执行post请求
public static void dopost(){
 // 创建httpclient对象
        closeablehttpclient httpclient = httpclientbuilder.create().setredirectstrategy(new laxredirectstrategy()).build();
 
        // 创建http post请求
        httppost httppost = new httppost("http://www.oschina.net/");
 
        closeablehttpresponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httppost);
            system.out.println(response.getstatusline());
            // 判断返回状态是否为200
            if (response.getstatusline().getstatuscode() == 200) {
                string content = entityutils.tostring(response.getentity(), "utf-8");
                system.out.println(content);
            }
        }catch(exception e){
         e.printstacktrace();
        
        }finally {
            if (response != null) {
                try {
response.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
            }
            try {
httpclient.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
        }
    }

 

 
执行post带参数
public static void dopostparam() throws exception{
 // 创建httpclient对象
        closeablehttpclient httpclient = httpclientbuilder.create().setredirectstrategy(new laxredirectstrategy()).build();
 
        // 创建http post请求
        httppost httppost = new httppost("http://www.oschina.net/search");
       
        // 设置2个post参数,一个是scope、一个是q
        list<namevaluepair> parameters = new arraylist<namevaluepair>();
        parameters.add(new basicnamevaluepair("scope", "project"));
        parameters.add(new basicnamevaluepair("q", "java"));
        // 构造一个form表单式的实体
        urlencodedformentity formentity = new urlencodedformentity(parameters);
        // 将请求实体设置到httppost对象中
        httppost.setentity(formentity);
 
        closeablehttpresponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httppost);
            system.out.println(response.getstatusline());
            // 判断返回状态是否为200
            if (response.getstatusline().getstatuscode() == 200) {
                string content = entityutils.tostring(response.getentity(), "utf-8");
                system.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
}

 

 
httpclient常见问题及解决方案
请求参数乱码
设置请求的编码格式:
obj.addheader("content-type","application/x-www-form-urlencoded; charset=utf-8");

 

 

 
响应http/1.1 403 forbidden
原因:网站设置了反爬虫机制,禁止非法访问。
解决方案:伪装浏览器。
obj.addheader("user-agent"," mozilla/5.0 (windows nt 6.1) applewebkit/537. 36 (khtml, like gecko) chrome/31.0.1650.63")

 

 

封装通用工具类httpclientutils
package org.chu.ego.base.utils;

import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import java.util.map;

import org.apache.http.httpentity;
import org.apache.http.namevaluepair;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.utils.uribuilder;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclientbuilder;
import org.apache.http.impl.client.httpclients;
import org.apache.http.impl.client.laxredirectstrategy;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.util.entityutils;
/**
 * --发送get请求的api
 * closeablehttpclient类 ,client实现类
 * httpclients类 ,client工具类,用于创建客户端对象。
 * closeablehttpresponse接口,请求的响应对象
 * uribuilder类 :url构建类,用于设置get请求的路径变量
 * httpget类 :get请求的发送对象
 * entityutils类 实体处理类
 * 
 * --发送post 请求使用的api
 * closeablehttpclient类
 * httpclientbuilder client构建对象,用于创建客户端对象。
 * laxredirectstrategy类,post请求重定向的策略
 * closeablehttpresponse 请求的响应对象
 * httppost post请求的发送对象
 * namevaluepair 类,用于设置参数值
 * urlencodedformentity:用于设置表单参数给发送对象httppost
 * 
 * @author ranger
 *
 */
public class httpclientutils {

public static string doget(string url,map<string, string> params){
        
        //获取httpclient客户端
        closeablehttpclient httpclient = httpclients.createdefault();
        
        string resultstring = "";
        
        closeablehttpresponse response = null;
        
        try {
            uribuilder builder = new uribuilder(url);
            
            if(null!=params){
                for (string key:params.keyset()) {
                    builder.setparameter(key, params.get(key));
                }
            }
            
            httpget get = new httpget(builder.build());
            
            
            response = httpclient.execute(get);
            
            system.out.println(response.getstatusline());
            
            if(200==response.getstatusline().getstatuscode()){
                httpentity entity = response.getentity();
                resultstring = entityutils.tostring(entity, "utf-8");
            }
            
        } catch (exception e) {
            
            e.printstacktrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (ioexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (ioexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
        }
        
        return resultstring;
    }
    
    public static string doget(string url){
        return doget(url, null);
    }
    
    public static string dopost(string url,map<string,string> params){
        /**
         * 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
         * 
         * 获取httpclient客户端
         */
        closeablehttpclient httpclient = httpclientbuilder.create().setredirectstrategy( new laxredirectstrategy()).build();
        
        string resultstring = "";
        
        closeablehttpresponse response = null;
        
        try {
            
            
            httppost post = new httppost(url);
            
            list<namevaluepair> paramaters = new arraylist<>();
            
            if(null!=params){
                for (string key : params.keyset()) {
                    paramaters.add(new basicnamevaluepair(key,params.get(key)));
                }
                
                urlencodedformentity  formentity = new urlencodedformentity (paramaters);
                
                post.setentity(formentity);
            }
            
            
            /**
             * http/1.1 403 forbidden
             *   原因:
             *      有些网站,设置了反爬虫机制
             *   解决的办法:
             *      设置请求头,伪装浏览器
             */
            post.addheader("user-agent", "mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/63.0.3239.132 safari/537.36");
            
            response = httpclient.execute(post);
            
            system.out.println(response.getstatusline());
            
            if(200==response.getstatusline().getstatuscode()){
                httpentity entity = response.getentity();
                resultstring = entityutils.tostring(entity, "utf-8");
            }
            
        } catch (exception e) {
            
            e.printstacktrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (ioexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (ioexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
        }
        
        return resultstring;
    }
    
    public static string dopost(string url){
        return dopost(url, null);
    }
 
}