java http token请求代码实例
本文实例为大家分享了javahttptoken的具体代码,供大家参考,具体内容如下
packagecom.monitoring.common.util; importjava.io.BufferedInputStream; importjava.io.BufferedReader; importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.net.HttpURLConnection; importjava.net.URL; importjava.net.URLEncoder; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjava.util.Set; importjava.util.regex.Matcher; importjava.util.regex.Pattern; importorg.apache.commons.httpclient.HttpClient; importorg.apache.commons.httpclient.MultiThreadedHttpConnectionManager; importorg.apache.commons.httpclient.NameValuePair; importorg.apache.commons.httpclient.methods.GetMethod; importorg.apache.commons.httpclient.methods.PostMethod; importorg.apache.commons.lang.StringUtils; importorg.apache.log4j.Logger; importorg.codehaus.jackson.JsonParseException; importorg.codehaus.jackson.map.JsonMappingException; /** *和HTTP相关的操作 * *@author * */ publicclassHttpUtils{ privatestaticfinalLoggerlogger=Logger.getLogger(HttpUtils.class); privatefinalstaticMultiThreadedHttpConnectionManagermanager=newMultiThreadedHttpConnectionManager(); //支持重复连接 privatestaticHttpClientclient=newHttpClient(manager); /** * *@Title:doPost *@Description:post请求 *@paramreqUrl *@paramparameters *@returnString */ publicstaticStringdoPost(StringreqUrl,Mapparameters,Stringtoken){ HttpURLConnectionurlConn=null; try{ urlConn=_sendPost(reqUrl,parameters,token); StringresponseContent=_getContent(urlConn); returnresponseContent.trim(); }finally{ if(urlConn!=null){ urlConn.disconnect(); } } } /** * *@Title:doUploadFile *@Description:从网络上下载文件 *@paramreqUrl *@paramparameters *@paramfileParamName *@paramfilename *@paramcontentType *@paramdata *@returnString */ publicstaticStringdoUploadFile(StringreqUrl,Map parameters,StringfileParamName, Stringfilename,StringcontentType,byte[]data){ HttpURLConnectionurlConn=null; try{ urlConn=_sendFormdata(reqUrl,parameters,fileParamName,filename,contentType,data); StringresponseContent=newString(_getBytes(urlConn)); returnresponseContent.trim(); }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); }finally{ if(urlConn!=null){ urlConn.disconnect(); } } } privatestaticHttpURLConnection_sendFormdata(StringreqUrl,Map parameters,StringfileParamName, Stringfilename,StringcontentType,byte[]data){ HttpURLConnectionurlConn=null; try{ URLurl=newURL(reqUrl); urlConn=(HttpURLConnection)url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(5000);//(单位:毫秒)jdk urlConn.setReadTimeout(5000);//(单位:毫秒)jdk1.5换成这个,读操作超时 urlConn.setDoOutput(true); urlConn.setRequestProperty("Connection","keep-alive"); Stringboundary="-----------------------------114975832116442893661388290519";//分隔符 urlConn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary); boundary="--"+boundary; StringBufferparams=newStringBuffer(); if(parameters!=null){ for(Iterator iter=parameters.keySet().iterator();iter.hasNext();){ Stringname=iter.next(); Stringvalue=parameters.get(name); params.append(boundary+"\r\n"); params.append("Content-Disposition:form-data;name=\""+name+"\"\r\n\r\n"); //params.append(URLEncoder.encode(value,"UTF-8")); params.append(value); params.append("\r\n"); } } StringBuildersb=newStringBuilder(); //sb.append("\r\n"); sb.append(boundary); sb.append("\r\n"); sb.append("Content-Disposition:form-data;name=\""+fileParamName+"\";filename=\""+filename +"\"\r\n"); sb.append("Content-Type:"+contentType+"\r\n\r\n"); byte[]fileDiv=sb.toString().getBytes(); byte[]endData=("\r\n"+boundary+"--\r\n").getBytes(); byte[]ps=params.toString().getBytes(); OutputStreamos=urlConn.getOutputStream(); os.write(ps); os.write(fileDiv); os.write(data); os.write(endData); os.flush(); os.close(); }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); } returnurlConn; } privatestaticString_getContent(HttpURLConnectionurlConn){ try{ StringresponseContent=null; InputStreamin=urlConn.getInputStream(); BufferedReaderrd=newBufferedReader(newInputStreamReader(in,"UTF-8")); StringtempLine=rd.readLine(); StringBuffertempStr=newStringBuffer(); Stringcrlf=System.getProperty("line.separator"); while(tempLine!=null){ tempStr.append(tempLine); tempStr.append(crlf); tempLine=rd.readLine(); } responseContent=tempStr.toString(); rd.close(); in.close(); returnresponseContent; }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); } } privatestaticbyte[]_getBytes(HttpURLConnectionurlConn){ try{ InputStreamin=urlConn.getInputStream(); ByteArrayOutputStreamos=newByteArrayOutputStream(); byte[]buf=newbyte[1024]; for(inti=0;(i=in.read(buf))>0;) os.write(buf,0,i); in.close(); returnos.toByteArray(); }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); } } privatestaticHttpURLConnection_sendPost(StringreqUrl,Map parameters,Stringtoken){ HttpURLConnectionurlConn=null; try{ StringBufferparams=newStringBuffer(); if(parameters!=null){ for(Iterator iter=parameters.keySet().iterator();iter.hasNext();){ Stringname=iter.next(); Stringvalue=parameters.get(name); params.append(name+"="); params.append(URLEncoder.encode(value,"UTF-8")); if(iter.hasNext()) params.append("&"); } } URLurl=newURL(reqUrl); urlConn=(HttpURLConnection)url.openConnection(); if(StringUtils.isNotBlank(token)){ urlConn.addRequestProperty("token",token); } urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(5000);//(单位:毫秒)jdk urlConn.setReadTimeout(5000);//(单位:毫秒)jdk1.5换成这个,读操作超时 urlConn.setDoOutput(true); byte[]b=params.toString().getBytes(); urlConn.getOutputStream().write(b,0,b.length); urlConn.getOutputStream().flush(); urlConn.getOutputStream().close(); }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); } returnurlConn; } /** *发送GET请求 * *@paramlink *@paramcharset *@return */ publicstaticStringdoGet(Stringlink,Stringcharset,Stringtoken){ HttpURLConnectionconn=null; try{ URLurl=newURL(link); conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent","Mozilla/5.0"); if(StringUtils.isNotEmpty(token)){ conn.addRequestProperty("token",token); } BufferedInputStreamin=newBufferedInputStream(conn.getInputStream()); ByteArrayOutputStreamout=newByteArrayOutputStream(); byte[]buf=newbyte[1024]; for(inti=0;(i=in.read(buf))>0;){ out.write(buf,0,i); } out.flush(); out.close(); Strings=newString(out.toByteArray(),charset); returns; }catch(Exceptione){ thrownewRuntimeException(e.getMessage(),e); }finally{ if(conn!=null){ conn.disconnect(); } } } /** *UTF-8编码 * *@paramlink *@return */ publicstaticStringdoGet(Stringlink,Stringtoken){ returndoGet(link,"UTF-8",token); } /** * *@Title:getIntResponse *@Description:发送GET请求 *@paramlink *@returnint */ publicstaticintgetIntResponse(Stringlink,Stringtoken){ Stringstr=doGet(link,token); returnInteger.parseInt(str.trim()); } publicstaticlongip2Long(StringstrIP){ long[]ip=newlong[4]; //先找到IP地址字符串中.的位置 intposition1=strIP.indexOf("."); intposition2=strIP.indexOf(".",position1+1); intposition3=strIP.indexOf(".",position2+1); //将每个.之间的字符串转换成整型 ip[0]=Long.parseLong(strIP.substring(0,position1)); ip[1]=Long.parseLong(strIP.substring(position1+1,position2)); ip[2]=Long.parseLong(strIP.substring(position2+1,position3)); ip[3]=Long.parseLong(strIP.substring(position3+1)); return(ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3]; } //将10进制整数形式转换成127.0.0.1形式的IP地址 publicstaticStringlong2IP(longlongIP){ StringBuffersb=newStringBuffer(""); //直接右移24位 sb.append(String.valueOf(longIP>>>24)); sb.append("."); //将高8位置0,然后右移16位 sb.append(String.valueOf((longIP&0x00FFFFFF)>>>16)); sb.append("."); sb.append(String.valueOf((longIP&0x0000FFFF)>>>8)); sb.append("."); sb.append(String.valueOf(longIP&0x000000FF)); returnsb.toString(); } /** * *urlParse:url解析.
* *@authormajun *@paramarrList *@paramurl *@return *@sinceJDK1.6 */ publicstaticMapurlParse(List arrList,Stringurl){ Map vaulesMap=newHashMap (); for(Strings:arrList){ Patternpattern=Pattern.compile(s+"=([^&]*)(&|$)"); Matchermatcher=pattern.matcher(url); if(matcher.find()){ String[]arr=matcher.group(1).split("'"); vaulesMap.put(s,arr[1]); } } returnvaulesMap; } /*** * *http_doPost:httpClient发送post请求.
* *@authormajun *@version创建时间:2016年6月22日下午6:15:59 *@sinceJDK1.6 */ publicstaticStringhttp_doPost(StringreqUrl,Mapparameters,StringuserToken){ try{ //MultiThreadedHttpConnectionManagermanager=newMultiThreadedHttpConnectionManager(); //支持重复连接 //HttpClientclient=newHttpClient(manager); PostMethodpost=newPostMethod(reqUrl); post.setRequestHeader("Connection","keep-alive"); post.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); NameValuePair[]params=newNameValuePair[parameters.size()]; Set keys=parameters.keySet(); intindex=0; for(Stringkey:keys){ params[index]=newNameValuePair(key,parameters.get(key)); index++; } post.setQueryString(params); if(StringUtils.isNotBlank(userToken)){ post.setRequestHeader("userToken",userToken); } Integerstatus=client.executeMethod(post); logger.info("loginStatus:"+status); Stringbody=post.getResponseBodyAsString(); returnbody; }catch(JsonParseExceptione){ e.printStackTrace(); }catch(JsonMappingExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } /*** * *http_doGet:httpClient发送get请求.
* *@authormajun *@version创建时间:2016年6月22日下午6:25:10 *@sinceJDK1.6 */ publicstaticStringhttp_doGet(StringreqUrl,Mapparameters,StringuserToken){ try{ //MultiThreadedHttpConnectionManagermanager=newMultiThreadedHttpConnectionManager(); //支持重复连接 //HttpClientclient=newHttpClient(manager); GetMethodget=newGetMethod(reqUrl); NameValuePair[]params=newNameValuePair[parameters.size()]; Set keys=parameters.keySet(); intindex=0; for(Stringkey:keys){ params[index]=newNameValuePair(key,parameters.get(key)); index++; } get.setQueryString(params); if(StringUtils.isNotBlank(userToken)){ get.setRequestHeader("userToken",userToken); } Integerstatus=client.executeMethod(get); logger.info("http_doGet==>Status:"+status); Stringbody=get.getResponseBodyAsString(); returnbody; }catch(Exceptione){ e.printStackTrace(); } returnnull; } }
以上所述是小编给大家介绍的javahttptoken请求详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!