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

Java 发送http请求(get、post)的示例

程序员文章站 2022-06-22 09:27:32
1.情景展示  java发送get请求、post请求(form表单、json数据)至另一服务器;  可设置http请求头部信息,可以接收服务器返回cookie信息,可以上传文件等;2.代码实现所需ja...

1.情景展示

  java发送get请求、post请求(form表单、json数据)至另一服务器;

  可设置http请求头部信息,可以接收服务器返回cookie信息,可以上传文件等; 

2.代码实现

所需jar包:httpcore-4.4.1.jar;httpclient-4.4.1.jar;httpmime-4.4.1.jar;epoint-utils-9.3.3.jar

import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.nio.charset.charset;
import java.security.generalsecurityexception;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import javax.net.ssl.hostnameverifier;
import javax.net.ssl.sslcontext;
import javax.net.ssl.sslsession;
import org.apache.http.header;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httpdelete;
import org.apache.http.client.methods.httpentityenclosingrequestbase;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppatch;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.methods.httprequestbase;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.conn.ssl.truststrategy;
import org.apache.http.entity.contenttype;
import org.apache.http.entity.stringentity;
import org.apache.http.entity.mime.multipartentitybuilder;
import org.apache.http.entity.mime.content.stringbody;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.impl.conn.poolinghttpclientconnectionmanager;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.ssl.sslcontextbuilder;
import org.apache.http.util.entityutils;
import com.epoint.core.utils.string.stringutil;
/**
 * httpclient工具类,使用http-client包实现,原先的common-httpclient已经淘汰
 *
 * @作者 ko
 * @version [版本号, 2017年10月18日]
 */
public class httputil
{
    private static poolinghttpclientconnectionmanager connmgr;
    private static requestconfig requestconfig;
    private static final int max_timeout = 7000;
 
    /**
     * 直接以流返回
     */
    public static final int rtn_type_1 = 1;
    /**
     * 直接以string返回
     */
    public static final int rtn_type_2 = 2;
    /**
     * 以map返回,reslut:接口结果string;statuscode:http状态码
     */
    public static final int rtn_type_3 = 3;
    /**
     * 以map返回,reslut:接口结果string;statuscode:http状态码;cookie:response的cookie
     * cookie值键值对,格式 key1=value1;key2=value2;...
     */
    public static final int rtn_type_4 = 4;
    /**
     * 默认上传文件的文件流或file 的key name
     */
    private static final string default_binarybody_keyname = "file";
 
    static {
        // 设置连接池
        connmgr = new poolinghttpclientconnectionmanager();
        // 设置连接池大小
        connmgr.setmaxtotal(100);
        connmgr.setdefaultmaxperroute(connmgr.getmaxtotal());
        // 在提交请求之前 测试连接是否可用
        connmgr.setvalidateafterinactivity(1);
 
        requestconfig.builder configbuilder = requestconfig.custom();
        // 设置连接超时
        configbuilder.setconnecttimeout(max_timeout);
        // 设置读取超时
        configbuilder.setsockettimeout(max_timeout);
        // 设置从连接池获取连接实例的超时
        configbuilder.setconnectionrequesttimeout(max_timeout);
        requestconfig = configbuilder.build();
    }
 
    /**
     * 发送 get请求
     *
     * @param apiurl
     *            api接口url
     * @return string 响应内容
     */
    public static string doget(string apiurl) {
        return dohttp(apiurl, null, "get", rtn_type_2);
    }
 
    /**
     * 发送post请求
     *
     * @param apiurl
     *            api接口url
     * @param params
     *            k-v参数
     * @return string 响应内容
     */
    public static string dopost(string apiurl, map<string, object> params) {
        return dohttp(apiurl, params, "post", rtn_type_2);
    }
 
    /**
     * 发送post请求
     *
     * @param apiurl
     *            api接口url
     * @param json
     *            json参数
     * @return string 响应内容
     */
    public static string dopostjson(string apiurl, string json) {
        return dohttp(apiurl, json, "post", rtn_type_2);
    }
 
    /**
     * 发送 http 请求
     *
     * @param apiurl
     *            api接口url
     * @param params
     *            {map<string, object> k-v形式、json字符串}
     * @param method
     *            {null、或者post:post请求、patch:patch请求、delete:delete请求、get:get请求}
     * @param type
     *            {httputil.rtn_type_1:请求返回stream(此时流需要在外部手动关闭);httputil.
     *            rtn_type_2:string;httputil.rtn_type_3:返回一个map,map包含结果(
     *            结果是string形式)以及http状态码;httputil.rtn_type_4:返回一个map,map包含结果(
     *            结果是string形式), http状态码和cookie;其他情况返回string}
     *            如果结果是个map,key为:result,statuscode,cookie,分别返回 结果
     *            string,http状态码,cookie; cookie值键值对,格式
     *            key1=value1;key2=value2;...
     * @return stream或 string 或 map
     */
    public static <t> t dohttp(string apiurl, object params, string method, int type) {
        return dohttp(apiurl, null, params, method, type);
    }
 
    /**
     * 发送 http 请求
     *
     * @param apiurl
     *            api接口url
     * @param headermap
     *            header信息map<string, string>,可设置cookie
     * @param params
     *            {map<string, object> k-v形式、json字符串}
     * @param method
     *            {null、或者post:post请求、patch:patch请求、delete:delete请求、get:get请求}
     * @param type
     *            {httputil.rtn_type_1:请求返回stream(此时流需要在外部手动关闭);httputil.
     *            rtn_type_2:string;httputil.rtn_type_3:返回一个map,map包含结果(
     *            结果是string形式)以及http状态码;httputil.rtn_type_4:返回一个map,map包含结果(
     *            结果是string形式), http状态码和cookie;其他情况返回string}
     *            如果结果是个map,key为:result,statuscode,cookie,分别返回 结果
     *            string,http状态码,cookie; cookie值键值对,格式
     *            key1=value1;key2=value2;...
     * @return stream或 string 或 map
     */
    public static <t> t dohttp(string apiurl, map<string, string> headermap, object params, string method, int type) {
        closeablehttpclient httpclient = null;
        if (isssl(apiurl)) {
            httpclient = httpclients.custom().setsslsocketfactory(createsslconnsocketfactory())
                    .setconnectionmanager(connmgr).setdefaultrequestconfig(requestconfig).build();
        }
        else {
            httpclient = httpclients.createdefault();
        }
        return dohttp(httpclient, apiurl, headermap, params, method, type);
    }
 
    /**
     * 发送 http 请求
     *
     * @param httpclient
     *            httpclient对象 由外部传入,用户 需要保持登录状态等情况 此时如果要ssl,那么要在外部加入ssl特性
     *            httpclient =
     *            httpclients.custom().setsslsocketfactory(httputil.
     *            createsslconnsocketfactory())
     *            .setconnectionmanager(httputil.getconnmgr()).
     *            setdefaultrequestconfig(httputil..getrequestconfig()).build();
     * @param apiurl
     *            api接口url
     * @param headermap
     *            header信息map<string, string>,可设置cookie
     *
     * @param params
     *            {map<string, object> k-v形式、json字符串}
     * @param method
     *            {null、或者post:post请求、patch:patch请求、delete:delete请求、get:get请求}
     * @param type
     *            {httputil.rtn_type_1:请求返回stream(此时流需要在外部手动关闭);httputil.
     *            rtn_type_2:string;httputil.rtn_type_3:返回一个map,map包含结果(
     *            结果是string形式)以及http状态码;httputil.rtn_type_4:返回一个map,map包含结果(
     *            结果是string形式), http状态码和cookie;其他情况返回string}
     *            如果结果是个map,key为:result,statuscode,cookie,分别返回 结果
     *            string,http状态码,cookie; cookie值键值对,格式
     *            key1=value1;key2=value2;...
     * @return stream或 string 或 map
     */
    @suppresswarnings("unchecked")
    public static <t> t dohttp(closeablehttpclient httpclient, string apiurl, map<string, string> headermap,
            object params, string method, int type) {
        httprequestbase httppost = null;
        if (stringutil.isnotblank(method)) {
            if ("patch".equalsignorecase(method)) {
                httppost = new httppatch(apiurl);
            }
            else if ("delete".equalsignorecase(method)) {
                httppost = new httpdelete(apiurl);
            }
            else if ("get".equalsignorecase(method)) {
                httppost = new httpget(apiurl);
            }
            else if ("post".equalsignorecase(method)) {
                httppost = new httppost(apiurl);
            }
        }
        else {
            httppost = new httppost(apiurl);
        }
        closeablehttpresponse response = null;
 
        try {
            // 设置header信息
            if (headermap != null && !headermap.isempty()) {
                for (map.entry<string, string> entry : headermap.entryset()) {
                    httppost.addheader(entry.getkey(), entry.getvalue());
                }
            }
            if (isssl(apiurl)) {
                httppost.setconfig(requestconfig);
            }
            // 参数不为null、要处理参数
            if (params != null) {
                // get请求拼接在url后面
                if (httppost instanceof httpget) {
                    stringbuffer param = new stringbuffer();
                    if (params instanceof map) {
                        map<string, object> paramsconvert = (map<string, object>) params;
                        int i = 0;
                        for (string key : paramsconvert.keyset()) {
                            if (i == 0)
                                param.append("?");
                            else
                                param.append("&");
                            param.append(key).append("=").append(paramsconvert.get(key));
                            i++;
                        }
                    }
                    else {
                        param.append("?" + params.tostring());
                    }
                    apiurl += param;
                }
                // delete请求暂不处理
                else if (!(httppost instanceof httpdelete)) {
                    // k-v形式
                    if (params instanceof map) {
                        map<string, object> paramsconvert = (map<string, object>) params;
 
                        list<namevaluepair> pairlist = new arraylist<>(paramsconvert.size());
                        for (map.entry<string, object> entry : paramsconvert.entryset()) {
                            namevaluepair pair = new basicnamevaluepair(entry.getkey(),
                                    entry.getvalue() == null ? "" : entry.getvalue().tostring());
                            pairlist.add(pair);
                        }
                        ((httpentityenclosingrequestbase) httppost)
                                .setentity(new urlencodedformentity(pairlist, charset.forname("utf-8")));
                    }
                    // json格式
                    else {
                        stringentity stringentity = new stringentity(params.tostring(), "utf-8");
                        stringentity.setcontentencoding("utf-8");
                        stringentity.setcontenttype("application/json");
                        ((httpentityenclosingrequestbase) httppost).setentity(stringentity);
                    }
                }
            }
            response = httpclient.execute(httppost);
            // int statuscode = response.getstatusline().getstatuscode();
            // if (statuscode != httpstatus.sc_ok) {
            // return null;
            // }
 
            httpentity entity = response.getentity();
            if (entity != null) {
                if (type == rtn_type_1) {
                    return (t) entity.getcontent();
                }
                else if (rtn_type_2 == type) {
                    return (t) entityutils.tostring(entity, "utf-8");
                }
                else if (rtn_type_3 == type || rtn_type_4 == type) {
                    map<string, string> rtnmap = new hashmap<string, string>();
                    rtnmap.put("result", entityutils.tostring(entity, "utf-8"));
                    rtnmap.put("statuscode", response.getstatusline().getstatuscode() + "");
                    if (rtn_type_4 == type) {
                        rtnmap.put("cookie", getcookie(response));
                    }
                    return (t) rtnmap;
                }
                else {
                    return (t) entityutils.tostring(entity, "utf-8");
                }
            }
        }
        catch (exception e) {
            e.printstacktrace();
        }
        finally {
            if (response != null && type != rtn_type_1) {
                try {
                    entityutils.consume(response.getentity());
                }
                catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param file
     *            可以选择本地文件上传;如果传了file,又传了filename,那么文件名以filename为准,否则 是file的文件名
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    public static string upload(string url, map<string, string> headermap, map<string, string> parammap, file file,
            string filename, boolean ssl) {
        return upload(url, headermap, parammap, file, null, filename, ssl);
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param in
     *            文件流
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    public static string upload(string url, map<string, string> headermap, map<string, string> parammap, inputstream in,
            string filename, boolean ssl) {
        return upload(url, headermap, parammap, null, in, filename, ssl);
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param httpclient
     *            外部传入httpclient
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param file
     *            可以选择本地文件上传;如果传了file,又传了filename,那么文件名以filename为准,否则 是file的文件名
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    public static string upload(closeablehttpclient httpclient, string url, map<string, string> headermap,
            map<string, string> parammap, file file, string filename, boolean ssl) {
        return upload(httpclient, url, headermap, parammap, file, null, filename, ssl);
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param httpclient
     *            外部传入httpclient
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param in
     *            文件流
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    public static string upload(closeablehttpclient httpclient, string url, map<string, string> headermap,
            map<string, string> parammap, inputstream in, string filename, boolean ssl) {
        return upload(httpclient, url, headermap, parammap, null, in, filename, ssl);
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param file
     *            可以选择本地文件上传,file,in互斥;如果传了file,又传了filename,那么文件名以filename为准,否则
     *            是file的文件名
     * @param in
     *            文件流
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    private static string upload(string url, map<string, string> headermap, map<string, string> parammap, file file,
            inputstream in, string filename, boolean ssl) {
        closeablehttpclient httpclient = null;
        if (ssl) {
            httpclient = httpclients.custom().setsslsocketfactory(createsslconnsocketfactory())
                    .setconnectionmanager(connmgr).setdefaultrequestconfig(requestconfig).build();
        }
        else {
            httpclient = httpclients.createdefault();
        }
        return upload(httpclient, url, headermap, parammap, file, in, filename, ssl);
    }
 
    /**
     * 上传附件(post形式)
     *
     * @param httpclient
     *            外部传入httpclient
     * @param url
     *            请求地址
     * @param headermap
     *            header参数map map<string, string>
     * @param parammap
     *            额外的参数map,map<string, string>
     * @param file
     *            可以选择本地文件上传,file,in互斥;如果传了file,又传了filename,那么文件名以filename为准,否则
     *            是file的文件名
     * @param in
     *            文件流
     * @param filename
     *            以流传输时,必须指定文件名
     * @param ssl
     *            是否需要ssl
     * @return result,返回上传结果,如果接口没有返回值,则为状态码
     */
    private static string upload(closeablehttpclient httpclient, string url, map<string, string> headermap,
            map<string, string> parammap, file file, inputstream in, string filename, boolean ssl) {
        string result = "";
        closeablehttpresponse response = null;
        try {
            httppost httppost = new httppost(url);
            // 设置header信息
            if (headermap != null && !headermap.isempty()) {
                for (map.entry<string, string> entry : headermap.entryset()) {
                    httppost.addheader(entry.getkey(), entry.getvalue());
                }
            }
            if (ssl) {
                httppost.setconfig(requestconfig);
            }
            multipartentitybuilder builder = multipartentitybuilder.create();
            // 选择以file形式上传
            if (file != null && file.exists()) {
                if (stringutil.isnotblank(filename)) {
                    builder.addbinarybody(default_binarybody_keyname, file, contenttype.default_binary, filename);
                }
                else {
                    builder.addbinarybody(default_binarybody_keyname, file);
                }
            }
            // 以流上传
            else if (in != null && stringutil.isnotblank(filename)) {
                builder.addbinarybody(default_binarybody_keyname, in, contenttype.default_binary, filename);
            }
            if (parammap != null && !parammap.isempty()) {
                for (map.entry<string, string> entry : parammap.entryset()) {
                    builder.addpart(entry.getkey(), new stringbody(entry.getvalue(), contenttype.text_plain));
                }
            }
            httpentity reqentity = builder.build();
            httppost.setentity(reqentity);
 
            response = httpclient.execute(httppost);
            httpentity entity = response.getentity();
            if (entity != null) {
                result = entityutils.tostring(entity, "utf-8");
            }
            else {
                result = response.getstatusline().getstatuscode() + "";
            }
        }
        catch (exception e) {
            e.printstacktrace();
        }
        finally {
            if (response != null) {
                try {
                    entityutils.consume(response.getentity());
                }
                catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
        return result;
    }
 
    private static string getcookie(httpresponse httpresponse) {
        map<string, string> cookiemap = new hashmap<string, string>(64);
        header headers[] = httpresponse.getheaders("set-cookie");
        if (headers == null || headers.length == 0) {
            return null;
        }
        string cookie = "";
        for (int i = 0; i < headers.length; i++) {
            cookie += headers[i].getvalue();
            if (i != headers.length - 1) {
                cookie += ";";
            }
        }
        string cookies[] = cookie.split(";");
        for (string c : cookies) {
            c = c.trim();
            if (cookiemap.containskey(c.split("=")[0])) {
                cookiemap.remove(c.split("=")[0]);
            }
            cookiemap.put(c.split("=")[0],
                    c.split("=").length == 1 ? "" : (c.split("=").length == 2 ? c.split("=")[1] : c.split("=", 2)[1]));
        }
        string cookiestmp = "";
        for (string key : cookiemap.keyset()) {
            cookiestmp += key + "=" + cookiemap.get(key) + ";";
        }
        return cookiestmp.substring(0, cookiestmp.length() - 2);
    }
 
    /**
     * 创建ssl安全连接
     *
     * @return
     */
    public static sslconnectionsocketfactory createsslconnsocketfactory() {
        sslconnectionsocketfactory sslsf = null;
        try {
            sslcontext sslcontext = new sslcontextbuilder().loadtrustmaterial(null, new truststrategy()
            {
 
                public boolean istrusted(x509certificate[] chain, string authtype) throws certificateexception {
                    return true;
                }
            }).build();
            sslsf = new sslconnectionsocketfactory(sslcontext, new hostnameverifier()
            {
 
                @override
                public boolean verify(string arg0, sslsession arg1) {
                    return true;
                }
            });
        }
        catch (generalsecurityexception e) {
            e.printstacktrace();
        }
        return sslsf;
    }
 
    public static poolinghttpclientconnectionmanager getconnmgr() {
        return connmgr;
    }
 
    public static requestconfig getrequestconfig() {
        return requestconfig;
    }
 
    private static boolean isssl(string apiurl) {
        if (apiurl.indexof("https") != -1 ) {
            return true;
        }
        else {
            return false;
        }
    }
 
}

以上就是java 发送http请求(get、post)的示例的详细内容,更多关于java 发送http请求的资料请关注其它相关文章!