尊龙游戏旗舰厅官网
收集整理的这篇文章主要介绍了
httpclient 讲解 (2) 项目封装
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
2019独角兽企业重金招聘python工程师标准>>>
org.apache.httpcomponents httpclient 4.3.4 org.apache.httpcomponents httpasyncclient 4.0.2 commons-httpclient commons-httpclient 3.1 package com.zefun.common.utils;import java.io.ioexception;
import java.io.unsupportedencodingexception;
import java.security.keymanagementexception;
import java.security.nosuchalgorithmexception;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import java.util.arraylist;
import java.util.list;
import java.util.map;import javax.net.ssl.sslcontext;
import javax.net.ssl.trustmanager;
import javax.net.ssl.x509trustmanager;import org.apache.commons.httpclient.httpstatus;
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.clientprotocolexception;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httpdelete;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.methods.httpput;
import org.apache.http.config.registry;
import org.apache.http.config.registrybuilder;
import org.apache.http.conn.socket.connectionsocketfactory;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.entity.stringentity;
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.conn.basichttpclientconnectionmanager;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.util.entityutils;
import org.apache.log4j.logger;/***
* @author
* @date 2015年8月11日 下午2:13:37*/
public class httpclientutil {/*** http协议*/private static final string https_protocol = "https://";/*** 协议默认端口*/private static final int https_protocol_default_port = 443;/*** 默认编码格式*/private static final string default_charset = "utf-8";/*** 日志*/private static logger logger = logger.getlogger(httpclientutil.class);/*** * @author * @date 2015年8月11日 下午2:16:57* @param url 路径* @return int*/private static int getport(string url) {int startindex = url.indexof("://") "://".length();string host = url.substring(startindex);if (host.indexof("/") != -1) {host = host.substring(0, host.indexof("/"));}int port = https_protocol_default_port;if (host.contains(":")) {int i = host.indexof(":");port = new integer(host.substring(i 1));}return port;}/*** * @author * @date 2015年8月11日 下午2:14:36* @param params 参数* @return list
*/private static list genenamevalpairs(map params) {list pairs = new arraylist();if (params == null) {return pairs;}for (string name : params.keyset()) {if (params.get(name) == null) {continue;}pairs.add(new basicnamevaluepair(name, params.get(name).tostring()));}return pairs;}/*** 发送get请求* @param url 请求地址* @param charset 返回数据编码* @return 返回数据*/public static string sendgetreq(final string url, string charset) {if (null == charset){charset = default_charset;}closeablehttpclient httpclient = httpclientbuilder.create().build();httpget get = new httpget(url);if (url.tolowercase().startswith(https_protocol)) {initssl(httpclient, getport(url));}try {// 提交请求并以指定编码获取返回数据httpresponse httpresponse = httpclient.execute(get);int statuscode = httpresponse.getstatusline().getstatuscode();if ((statuscode == httpstatus.sc_moved_temporarily) || (statuscode == httpstatus.sc_moved_permanently)|| (statuscode == httpstatus.sc_see_other) || (statuscode == httpstatus.sc_temporary_redirect)) {header header = httpresponse.getfirstheader("location");if (header != null) {string newuri = header.getvalue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}logger.info("重定向地址:" newuri);return sendgetreq(newuri, null);}}logger.info("请求地址:" url ";响应状态:" httpresponse.getstatusline());httpentity entity = httpresponse.getentity();return entityutils.tostring(entity, charset);}catch (clientprotocolexception e) {logger.error("协议异常,堆栈信息如下", e);}catch (ioexception e) {logger.error("网络异常,堆栈信息如下", e);}finally {// 关闭连接,释放资源try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}}return null;}/*** 发送put请求* @param url 请求地址* @param params 请求参数* @param charset 返回数据编码* @return string*/public static string sendputreq(string url, map params, string charset) {if (null == charset){charset = default_charset;}closeablehttpclient httpclient = httpclientbuilder.create().build();httpput put = new httpput(url);// 封装请求参数list pairs = genenamevalpairs(params);try {put.setentity(new urlencodedformentity(pairs, charset));if (url.startswith(https_protocol)) {initssl(httpclient, getport(url));}// 提交请求并以指定编码获取返回数据httpresponse httpresponse = httpclient.execute(put);logger.info("请求地址:" url ";响应状态:" httpresponse.getstatusline());httpentity entity = httpresponse.getentity();return entityutils.tostring(entity, charset);}catch (clientprotocolexception e) {logger.error("协议异常,堆栈信息如下", e);}catch (ioexception e) {logger.error("网络异常,堆栈信息如下", e);}finally {// 关闭连接,释放资源try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}}return null;}/*** 发送delete请求* @param url 请求地址* @param charset 返回数据编码* @return string*/public static string senddelreq(string url, string charset) {if (null == charset){charset = default_charset;}closeablehttpclient httpclient = httpclientbuilder.create().build();httpdelete del = new httpdelete(url);if (url.tolowercase().startswith(https_protocol)) {initssl(httpclient, getport(url));}try {// 提交请求并以指定编码获取返回数据httpresponse httpresponse = httpclient.execute(del);logger.info("请求地址:" url ";响应状态:" httpresponse.getstatusline());httpentity entity = httpresponse.getentity();return entityutils.tostring(entity, charset);}catch (clientprotocolexception e) {logger.error("协议异常,堆栈信息如下", e);}catch (ioexception e) {logger.error("网络异常,堆栈信息如下", e);}finally {// 关闭连接,释放资源try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}}return null;}/*** 发送post请求,支持http与https* @param url 请求地址* @param params 请求参数* @param charset 返回数据编码* @return 返回数据*/public static string sendpostreq(string url, map params, string charset) {if (null == charset){charset = default_charset;}closeablehttpclient httpclient = httpclientbuilder.create().build();requestconfig reqconf = requestconfig.default;httppost httppost = new httppost(url);// 封装请求参数list pairs = genenamevalpairs(params);try {httppost.setentity(new urlencodedformentity(pairs, charset));// 对https请求进行处理if (url.tolowercase().startswith(https_protocol)) {initssl(httpclient, getport(url));}// 提交请求并以指定编码获取返回数据httppost.setconfig(reqconf);httpresponse httpresponse = httpclient.execute(httppost);int statuscode = httpresponse.getstatusline().getstatuscode();if ((statuscode == httpstatus.sc_moved_temporarily) || (statuscode == httpstatus.sc_moved_permanently)|| (statuscode == httpstatus.sc_see_other) || (statuscode == httpstatus.sc_temporary_redirect)) {header header = httpresponse.getfirstheader("location");if (header != null) {string newuri = header.getvalue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}return sendgetreq(newuri, null);}}logger.info("请求地址:" url ";响应状态:" httpresponse.getstatusline());httpentity entity = httpresponse.getentity();return entityutils.tostring(entity, charset);}catch (unsupportedencodingexception e) {logger.error("不支持当前参数编码格式[" charset "],堆栈信息如下", e);}catch (clientprotocolexception e) {logger.error("协议异常,堆栈信息如下", e);}catch (ioexception e) {logger.error("网络异常,堆栈信息如下", e);}finally {// 关闭连接,释放资源try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}}return null;}/*** 发送post请求,支持http与https, 参数放入请求体方式* @param url 请求地址* @param content 请求参数* @param charset 返回数据编码* @return 返回数据*/public static string sendpost(string url, string content, string charset) {if (null == charset){charset = default_charset;}closeablehttpclient httpclient = httpclientbuilder.create().build();requestconfig reqconf = requestconfig.default;httppost httppost = new httppost(url);try {httppost.setentity(new stringentity(content, charset));// 对https请求进行处理if (url.tolowercase().startswith(https_protocol)) {initssl(httpclient, getport(url));}// 提交请求并以指定编码获取返回数据httppost.setconfig(reqconf);httpresponse httpresponse = httpclient.execute(httppost);int statuscode = httpresponse.getstatusline().getstatuscode();if ((statuscode == httpstatus.sc_moved_temporarily) || (statuscode == httpstatus.sc_moved_permanently)|| (statuscode == httpstatus.sc_see_other) || (statuscode == httpstatus.sc_temporary_redirect)) {header header = httpresponse.getfirstheader("location");if (header != null) {string newuri = header.getvalue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}return sendgetreq(newuri, null);}}logger.info("请求地址:" url ";响应状态:" httpresponse.getstatusline());httpentity entity = httpresponse.getentity();return entityutils.tostring(entity, charset);}catch (unsupportedencodingexception e) {logger.error("不支持当前参数编码格式[" charset "],堆栈信息如下", e);}catch (clientprotocolexception e) {logger.error("协议异常,堆栈信息如下", e);}catch (ioexception e) {logger.error("网络异常,堆栈信息如下", e);}finally {// 关闭连接,释放资源try {httpclient.close();}catch (exception e) {e.printstacktrace();httpclient = null;}}return null;}/*** 初始化https请求服务* @param httpclient http客户端* @param port 端口*/public static void initssl(closeablehttpclient httpclient, int port) {sslcontext sslcontext = null;try {sslcontext = sslcontext.getinstance("ssl");final x509trustmanager trustmanager = new x509trustmanager() {public void checkclienttrusted(x509certificate[] arg0, string arg1) throws certificateexception {}public void checkservertrusted(x509certificate[] arg0, string arg1) throws certificateexception {}public x509certificate[] getacceptedissuers() {return null;}};// 使用trustmanager来初始化该上下文,trustmanager只是被ssl的socket所使用sslcontext.init(null, new trustmanager[] { trustmanager }, null);connectionsocketfactory ssf = new sslconnectionsocketfactory(sslcontext);registry r = registrybuilder. create().register("https", ssf).build();basichttpclientconnectionmanager ccm = new basichttpclientconnectionmanager(r);httpclients.custom().setconnectionmanager(ccm).build();}catch (keymanagementexception e) {e.printstacktrace();}catch (nosuchalgorithmexception e) {e.printstacktrace();}}
} string url = "http://up.qiniu.com/putb64/-1";httppost post = new httppost(url);post.addheader("content-type", "application/octet-stream");post.addheader("authorization", "uptoken " qiniuuptoken().get("uptoken"));//post.setentity(new bytearrayentity(src));post.setentity(new stringentity(stringbase64));httpclient c = http.getclient();httpresponse res = c.execute(post);system.out.println(res.getstatusline().getreasonphrase());string responsebody = entityutils.tostring(res.getentity(), config.charset);system.out.println(responsebody); 基于file上传 file file = new file("d:\\1.jpg");filebody body = new filebody(file);multipartentity entity = new multipartentity();//注意file是在后台中接受的参数file fileentity.addpart("file", body);httppost.setentity(entity); 基于流上传 inputstreambody inputstreambody = new inputstreambody(new fileinputstream(file), file.getname());multipartentity entity = new multipartentity();//注意file是在后台中接受的参数file fileentity.addpart("file", inputstreambody);httppost.setentity(entity); 后台接受都是一样的
@requestmapping(value = url.project.upload_project)public basedto uploadtest(@requestparam(value = "file", required = false) multipartfile file, httpservletrequest request){string path = request.getsession().getservletcontext().getrealpath("upload"); string filename = file.getoriginalfilename(); file targetfile = new file(path, filename); if (!targetfile.exists()){ targetfile.mkdir();} try { file.transferto(targetfile); } catch (exception e) { e.printstacktrace(); }return new basedto(app.system.api_result_code_for_succees, app.system.api_result_msg_for_succees);}
转载于:https://my.oschina.net/gaoguofan/blog/752914
总结
以上是尊龙游戏旗舰厅官网 为你收集整理的httpclient 讲解 (2) 项目封装 的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得尊龙游戏旗舰厅官网 网站内容还不错,欢迎将尊龙游戏旗舰厅官网 推荐给好友。