分享
 
 
 

Java ME平台中的URLEncoder实现类

王朝java/jsp·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

这个类是从Java.net.URLEncoder修改来的 经测试能够正常完成URL编码的工作,在几部手机上测试过。使用的时候直接调用URLEncoder.encode("中国")即可 如果向服务器端发送。可以使用如下的办法对中文进行编码,然后发送向服务器。

String data = "para="+URLEncoder.encode("参数");

outputStream.write(data.getBytes());

.......

在服务器端 以servlet为例 request.getParameter("para")即可获得“参数”

package com.j2medev.httpme.tools;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;

/**

* Utility class for form encoding.this class is modified form java.net.URLEncoder so that it can work well in cldc env.

* This class contains static methods

* for converting a String to the <CODE>application/x-www-form-urlencoded</CODE> MIME

* format. For more information about Html form encoding, consult the HTML

* <A HREF="http://www.w3.org/TR/html4/">specification</A>.

*

* <p>

* When encoding a String, the following rules apply:

*

* <p>

* <ul>

* <li>The alphanumeric characters "<code>a</code>" through

* "<code>z</code>", "<code>A</code>" through

* "<code>Z</code>" and "<code>0</code>"

* through "<code>9</code>" remain the same.

* <li>The special characters "<code>.</code>",

* "<code>-</code>", "<code>*</code>", and

* "<code>_</code>" remain the same.

* <li>The space character "<code> </code>" is

* converted into a plus sign "<code>+</code>".

* <li>All other characters are unsafe and are first converted into

* one or more bytes using some encoding scheme. Then each byte is

* represented by the 3-character string

* "<code>%<i>xy</i></code>", where <i>xy</i> is the

* two-digit hexadecimal representation of the byte.

* The recommended encoding scheme to use is UTF-8. However,

* for compatibility reasons, if an encoding is not specified,

* then the default encoding of the platform is used.

* </ul>

*

* <p>

* For example using UTF-8 as the encoding scheme the string "The

* string ü@foo-bar" would get converted to

* "The+string+%C3%BC%40foo-bar" because in UTF-8 the character

* ü is encoded as two bytes C3 (hex) and BC (hex), and the

* character @ is encoded as one byte 40 (hex).

*

* @author mingjava

* @version 0.1 05/06/2006

* @since httpme 0.1

*/

public class URLEncoder {

/** The characters which do not need to be encoded. */

private static boolean[] dontNeedEncoding;

private static String defaultEncName = "";

static final int caseDiff = ('a' - 'A');

static {

dontNeedEncoding = new boolean[256];

int i;

for (i = 'a'; i <= 'z'; i++) {

dontNeedEncoding[i] = true;

}

for (i = 'A'; i <= 'Z'; i++) {

dontNeedEncoding[i] = true;

}

for (i = '0'; i <= '9'; i++) {

dontNeedEncoding[i] = true;

}

dontNeedEncoding[' '] = true; // encoding a space to a + is done in the encode() method

dontNeedEncoding['-'] = true;

dontNeedEncoding['_'] = true;

dontNeedEncoding['.'] = true;

dontNeedEncoding['*'] = true;

defaultEncName = System.getProperty("microedition.encoding");

if(defaultEncName == null defaultEncName.trim().length() == 0){

defaultEncName = "UTF-8";

}

}

public static final int MIN_RADIX = 2;

/**

* The maximum radix available for conversion to and from strings.

*/

public static final int MAX_RADIX = 36;

/**

* The class is not meant to be instantiated.

*/

private URLEncoder() { }

/**

* Translates a string into "<CODE>x-www-form-urlencoded</CODE>"

* format.This method uses the platform's default encoding

* as the encoding scheme to oBTain the bytes for unsafe characters.

*

* @param s the string to be translated.

*

* @return The resulting string.

*/

public static String encode(String s) {

String str = null;

str = encode(s, defaultEncName);

return str;

}

/**

* Translates a string into <code>application/x-www-form-urlencoded</code>

* format using a specific encoding scheme. This method uses the

* supplied encoding scheme to obtain the bytes for unsafe

* characters.

* <p>

* <em><strong>Note:</strong> The <a href=

* "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">

* World Wide Web Consortium Recommendation</a> states that

* UTF-8 should be used. Not doing so may introdUCe

* incompatibilites.</em>

*

* @param s <code>String</code> to be translated.

* @param enc The name of a supported character encoding such as UTF-8

* @return the translated <code>String</code>.

*/

public static String encode(String s, String enc) {

boolean needToChange = false;

boolean wroteUnencodedChar = false;

int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now

StringBuffer out = new StringBuffer(s.length());

ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);

OutputStreamWriter writer = null;

try {

writer = new OutputStreamWriter(buf, enc);

} catch (UnsupportedEncodingException ex) {

try {

writer = new OutputStreamWriter(buf,defaultEncName);

} catch (UnsupportedEncodingException e) {

//never reach

}

}

for (int i = 0; i < s.length(); i++) {

int c = (int) s.charAt(i);

//System.out.println("Examining character: " + c);

if (c <256 && dontNeedEncoding[c]) {

if (c == ' ') {

c = '+';

needToChange = true;

}

//System.out.println("Storing: " + c);

out.append((char)c);

wroteUnencodedChar = true;

} else {

// convert to external encoding before hex conversion

try {

if (wroteUnencodedChar) { // Fix for 4407610

writer = new OutputStreamWriter(buf, enc);

wroteUnencodedChar = false;

}

if(writer !

= null)

writer.write(c);

/*

* If this character represents the start of a Unicode

* surrogate pair, then pass in two characters. It's not

* clear what should be done if a bytes reserved in the

* surrogate pairs range occurs outside of a legal

* surrogate pair. For now, just treat it as if it were

* any other character.

*/

if (c >= 0xD800 && c <= 0xDBFF) {

/*

System.out.println(Integer.toHexString(c)

+ " is high surrogate");

*/

if ( (i+1) < s.length()) {

int d = (int) s.charAt(i+1);

/*

System.out.println("\tExamining "

+ Integer.toHexString(d));

*/

if (d >= 0xDC00 && d <= 0xDFFF) {

/*

System.out.println("\t"

+ Integer.toHexString(d)

+ " is low surrogate");

*/

writer.write(d);

i++;

}

}

}

writer.flush();

} catch(IOException e) {

buf.reset();

continue;

}

byte[] ba = buf.toByteArray();

for (int j = 0; j < ba.length; j++) {

out.append('%');

char ch = forDigit((ba[j] >> 4) & 0xF, 16);

if (isLetter(ch)) {

ch -= caseDiff;

}

out.append(ch);

ch = forDigit((ba[j] & 0xF), 16);

//ch = forDigit(ba[j] & 0xF, 16);

if (isLetter(ch)) {

ch -= caseDiff;

}

out.append(ch);

}

buf.reset();

needToChange = true;

}

}

return (needToChange?

out.toString() : s);

}

private static boolean isLetter(char c){

if( (c >= 'a' && c <= 'z') (c >='A' && c <= 'Z'))

return true;

return false;

}

private static char forDigit(int digit,int radix){

if ((digit >= radix) (digit < 0)) {

return '\0'; }

if ((radix < MIN_RADIX) (radix > MAX_RADIX)) {

return '\0';

}

if (digit < 10) {

return (char)('0' + digit);

}

return (char)('a' - 10 + digit);

}

}

(出处:http://www.knowsky.com)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有