本文實例為大家分享了java http token的具體代碼,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
|
package com.monitoring.common.util; import java.io.bufferedinputstream; import java.io.bufferedreader; import java.io.bytearrayoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.net.httpurlconnection; import java.net.url; import java.net.urlencoder; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import java.util.set; import java.util.regex.matcher; import java.util.regex.pattern; import org.apache.commons.httpclient.httpclient; import org.apache.commons.httpclient.multithreadedhttpconnectionmanager; import org.apache.commons.httpclient.namevaluepair; import org.apache.commons.httpclient.methods.getmethod; import org.apache.commons.httpclient.methods.postmethod; import org.apache.commons.lang.stringutils; import org.apache.log4j.logger; import org.codehaus.jackson.jsonparseexception; import org.codehaus.jackson.map.jsonmappingexception; /** * 和http相關的操作 * * @author * */ public class httputils { private static final logger logger = logger.getlogger(httputils. class ); private final static multithreadedhttpconnectionmanager manager = new multithreadedhttpconnectionmanager(); // 支持重復連接 private static httpclient client = new httpclient(manager); /** * * @title: dopost * @description: post請求 * @param requrl * @param parameters * @return string */ public static string dopost(string requrl, map<string, string> parameters, string token) { httpurlconnection urlconn = null ; try { urlconn = _sendpost(requrl, parameters, token); string responsecontent = _getcontent(urlconn); return responsecontent.trim(); } finally { if (urlconn != null ) { urlconn.disconnect(); } } } /** * * @title: douploadfile * @description: 從網絡上下載文件 * @param requrl * @param parameters * @param fileparamname * @param filename * @param contenttype * @param data * @return string */ public static string douploadfile(string requrl, map<string, string> parameters, string fileparamname, string filename, string contenttype, byte [] data) { httpurlconnection urlconn = null ; try { urlconn = _sendformdata(requrl, parameters, fileparamname, filename, contenttype, data); string responsecontent = new string(_getbytes(urlconn)); return responsecontent.trim(); } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } finally { if (urlconn != null ) { urlconn.disconnect(); } } } private static httpurlconnection _sendformdata(string requrl, map<string, string> parameters, string fileparamname, string filename, string contenttype, byte [] data) { httpurlconnection urlconn = null ; try { url url = new url(requrl); urlconn = (httpurlconnection) url.openconnection(); urlconn.setrequestmethod( "post" ); urlconn.setconnecttimeout( 5000 ); // (單位:毫秒)jdk urlconn.setreadtimeout( 5000 ); // (單位:毫秒)jdk 1.5換成這個,讀操作超時 urlconn.setdooutput( true ); urlconn.setrequestproperty( "connection" , "keep-alive" ); string boundary = "-----------------------------114975832116442893661388290519" ; // 分隔符 urlconn.setrequestproperty( "content-type" , "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; stringbuffer params = new stringbuffer(); if (parameters != null ) { for (iterator<string> iter = parameters.keyset().iterator(); iter.hasnext();) { string name = iter.next(); string value = 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" ); } } stringbuilder sb = new stringbuilder(); // 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(); outputstream os = urlconn.getoutputstream(); os.write(ps); os.write(filediv); os.write(data); os.write(enddata); os.flush(); os.close(); } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } return urlconn; } private static string _getcontent(httpurlconnection urlconn) { try { string responsecontent = null ; inputstream in = urlconn.getinputstream(); bufferedreader rd = new bufferedreader( new inputstreamreader(in, "utf-8" )); string templine = rd.readline(); stringbuffer tempstr = new stringbuffer(); string crlf = system.getproperty( "line.separator" ); while (templine != null ) { tempstr.append(templine); tempstr.append(crlf); templine = rd.readline(); } responsecontent = tempstr.tostring(); rd.close(); in.close(); return responsecontent; } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } } private static byte [] _getbytes(httpurlconnection urlconn) { try { inputstream in = urlconn.getinputstream(); bytearrayoutputstream os = new bytearrayoutputstream(); byte [] buf = new byte [ 1024 ]; for ( int i = 0 ; (i = in.read(buf)) > 0 ;) os.write(buf, 0 , i); in.close(); return os.tobytearray(); } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } } private static httpurlconnection _sendpost(string requrl, map<string, string> parameters, string token) { httpurlconnection urlconn = null ; try { stringbuffer params = new stringbuffer(); if (parameters != null ) { for (iterator<string> iter = parameters.keyset().iterator(); iter.hasnext();) { string name = iter.next(); string value = parameters.get(name); params.append(name + "=" ); params.append(urlencoder.encode(value, "utf-8" )); if (iter.hasnext()) params.append( "&" ); } } url url = new url(requrl); urlconn = (httpurlconnection) url.openconnection(); if (stringutils.isnotblank(token)) { urlconn.addrequestproperty( "token" , token); } urlconn.setrequestmethod( "post" ); urlconn.setconnecttimeout( 5000 ); // (單位:毫秒)jdk urlconn.setreadtimeout( 5000 ); // (單位:毫秒)jdk 1.5換成這個,讀操作超時 urlconn.setdooutput( true ); byte [] b = params.tostring().getbytes(); urlconn.getoutputstream().write(b, 0 , b.length); urlconn.getoutputstream().flush(); urlconn.getoutputstream().close(); } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } return urlconn; } /** * 發送get請求 * * @param link * @param charset * @return */ public static string doget(string link, string charset, string token) { httpurlconnection conn = null ; try { url url = new url(link); conn = (httpurlconnection) url.openconnection(); conn.setrequestmethod( "get" ); conn.setrequestproperty( "user-agent" , "mozilla/5.0" ); if (stringutils.isnotempty(token)) { conn.addrequestproperty( "token" , token); } bufferedinputstream in = new bufferedinputstream(conn.getinputstream()); bytearrayoutputstream out = new bytearrayoutputstream(); byte [] buf = new byte [ 1024 ]; for ( int i = 0 ; (i = in.read(buf)) > 0 ;) { out.write(buf, 0 , i); } out.flush(); out.close(); string s = new string(out.tobytearray(), charset); return s; } catch (exception e) { throw new runtimeexception(e.getmessage(), e); } finally { if (conn != null ) { conn.disconnect(); } } } /** * utf-8編碼 * * @param link * @return */ public static string doget(string link, string token) { return doget(link, "utf-8" , token); } /** * * @title: getintresponse * @description: 發送get請求 * @param link * @return int */ public static int getintresponse(string link, string token) { string str = doget(link, token); return integer.parseint(str.trim()); } public static long ip2long(string strip) { long [] ip = new long [ 4 ]; // 先找到ip地址字符串中.的位置 int position1 = strip.indexof( "." ); int position2 = strip.indexof( "." , position1 + 1 ); int position3 = 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地址 public static string long2ip( long longip) { stringbuffer sb = new stringbuffer( "" ); // 直接右移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 )); return sb.tostring(); } /** * * urlparse:url解析. <br/> * * @author majun * @param arrlist * @param url * @return * @since jdk 1.6 */ public static map<string, string> urlparse(list<string> arrlist, string url) { map<string, string> vaulesmap = new hashmap<string, string>(); for (string s : arrlist) { pattern pattern = pattern.compile(s + "=([^&]*)(&|$)" ); matcher matcher = pattern.matcher(url); if (matcher.find()) { string[] arr = matcher.group( 1 ).split( "'" ); vaulesmap.put(s, arr[ 1 ]); } } return vaulesmap; } /*** * * http_dopost: httpclient發送post 請求. <br/> * * @author majun * @version 創建時間:2016年6月22日 下午6:15:59 * @since jdk 1.6 */ public static string http_dopost(string requrl, map<string, string> parameters, string usertoken) { try { // multithreadedhttpconnectionmanager manager = new multithreadedhttpconnectionmanager(); // 支持重復連接 // httpclient client = new httpclient(manager); postmethod post = new postmethod(requrl); post.setrequestheader( "connection" , "keep-alive" ); post.setrequestheader( "content-type" , "application/x-www-form-urlencoded" ); namevaluepair[] params = new namevaluepair[parameters.size()]; set<string> keys = parameters.keyset(); int index = 0 ; for (string key : keys) { params[index] = new namevaluepair(key, parameters.get(key)); index++; } post.setquerystring(params); if (stringutils.isnotblank(usertoken)) { post.setrequestheader( "usertoken" , usertoken); } integer status = client.executemethod(post); logger.info( "loginstatus:" + status); string body = post.getresponsebodyasstring(); return body; } catch (jsonparseexception e) { e.printstacktrace(); } catch (jsonmappingexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } return null ; } /*** * * http_doget: httpclient發送get請求. <br/> * * @author majun * @version 創建時間:2016年6月22日 下午6:25:10 * @since jdk 1.6 */ public static string http_doget(string requrl, map<string, string> parameters, string usertoken) { try { // multithreadedhttpconnectionmanager manager = new multithreadedhttpconnectionmanager(); // 支持重復連接 // httpclient client = new httpclient(manager); getmethod get = new getmethod(requrl); namevaluepair[] params = new namevaluepair[parameters.size()]; set<string> keys = parameters.keyset(); int index = 0 ; for (string key : keys) { params[index] = new namevaluepair(key, parameters.get(key)); index++; } get.setquerystring(params); if (stringutils.isnotblank(usertoken)) { get.setrequestheader( "usertoken" , usertoken); } integer status = client.executemethod(get); logger.info( "http_doget==>status:" + status); string body = get.getresponsebodyasstring(); return body; } catch (exception e) { e.printstacktrace(); } return null ; } } |
以上所述是小編給大家介紹的java http token請求詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/qq_33212500/article/details/79229897