---
title: "J2ME URLDecoder UTF-8"
author: "ripotala"
date: "2008-12-04T14:39:00Z"
tags: []
slug: "j2me-urldecoder-utf-8"
draft: false
lastmod: "2013-09-07T15:57:07Z"
id: 1938457
url: "https://ripotala.iteye.com/blog/1938457"
---

01. publicclassURL{
02. /\**
03. \*解码URL串
04. \*
05. \*@paramurl待解码的URL串
06. \*@return解码后的字符串
07. \*/
08. publicstaticStringdecode(Stringurl){
09. char\[]chars=url.toCharArray();
10. intcursor=0;
11. ByteArrayOutputStreambaos=newByteArrayOutputStream();
12. DataOutputStreamdos=null;
13. try{
14. dos=newDataOutputStream(baos);
15. while(cursor&lt;chars.length){
16. intcurr=chars\[cursor++];
17. if(curr=='%'){
18. StringBuffertmp=newStringBuffer();
19. charcr=chars\[cursor++];
20. charlf=chars\[cursor++];
21. tmp.append(cr).append(lf);
22. Integerresult=Integer.valueOf(tmp.toString(),16);
23. curr=result.intValue();
24. }
25. dos.writeByte(curr);
26. }
27. dos.flush();
28. baos.flush();
29. byte\[]data=baos.toByteArray();
30. Stringtext=UTF8.decode(data,0,data.length);
31. returntext;
32. }catch(Exceptione){
33. e.printStackTrace();
34. }finally{
35. try{
36. if(dos!=null)dos.close();
37. if(baos!=null)baos.close();
38. }catch(Exceptione){
39. }
40. }
41. returnnull;
42. }
43. }
44. publicclassUTF8{
45. publicstaticStringdecode(bytein\[],intoffset,intlength){
46. StringBufferbuff=newStringBuffer();
47. intmax=offset+length;
48. for(inti=offset;i&lt;max;i++){
49. charc=0;
50. if((in\[i]&0x80)==0){
51. c=(char)in\[i];
52. }elseif((in\[i]&0xe0)==0xc0){//11100000
53. c|=((in\[i++]&0x1f)&lt;&lt;6);//00011111
54. c|=((in\[i]&0x3f)&lt;&lt;0);//00111111
55. }elseif((in\[i]&0xf0)==0xe0){//11110000
56. c|=((in\[i++]&0x0f)&lt;&lt;12);//00001111
57. c|=((in\[i++]&0x3f)&lt;&lt;6);//00111111
58. c|=((in\[i]&0x3f)&lt;&lt;0);//00111111
59. }elseif((in\[i]&0xf8)==0xf0){//11111000
60. c|=((in\[i++]&0x07)&lt;&lt;18);//00000111(move18,not16?)
61. c|=((in\[i++]&0x3f)&lt;&lt;12);//00111111
62. c|=((in\[i++]&0x3f)&lt;&lt;6);//00111111
63. c|=((in\[i]&0x3f)&lt;&lt;0);//00111111
64. }else{
65. c='?';
66. }
67. buff.append(c);
68. }
69. returnbuff.toString();
70. }
71. }