Android http请求例子、Unicode转UTF-8 java代码收藏

Android项目经常是C/S模型的,因此需要向服务器发出http请求,收藏一个http请求的例子以便以后可以用。

假设发出的请求使用get方法,服务器传回JSON数据,解析代码如下:

HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(req_url);
try {
	HttpResponse response = client.execute(httpGet);
	int statusCode = response.getStatusLine().getStatusCode();
	if (statusCode != HttpStatus.SC_OK) {
		Log.d("AD", "statusCode is " + statusCode);
		return null;
	} 
	else {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream inputStream = entity.getContent();
			StringBuilder builder = new StringBuilder();
			BufferedReader bufferedReader  = new BufferedReader(new InputStreamReader(inputStream));
			for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
				builder.append(s);
			}
			String result = builder.toString();
					
			Log.d("AD", "Server return " + result);
			return result;
					
		}
	} 
} catch (Exception e) {
	httpGet.abort();
	Log.d("AD", "when http get, exception is " + e.getMessage());
}
return null;

注:JSON数据格式其实就是String。可以用JSONObject类进行转化。


有时候服务器传回的数据中会遇到传回数据为Unicode的情况,为此需要进行Unicode转UTF-8的转化,我在项目中遇见过,为此收藏一份转化 java 代码,便于以后使用:

private static String decodeUnicode(String theString) {
	char aChar;
	int len = theString.length();
	StringBuffer outBuffer = new StringBuffer(len);
	for (int x = 0; x < len;) {
		aChar = theString.charAt(x++);
		if (aChar == '\\') {
			aChar = theString.charAt(x++);
			if (aChar == 'u') {
				// Read the xxxx
				int value = 0;
				for (int i = 0; i < 4; i++) {
					aChar = theString.charAt(x++);
					switch (aChar) {
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						value = (value << 4) + aChar - '0';
						break;
					case 'a':
					case 'b':
					case 'c':
					case 'd':
					case 'e':
					case 'f':
						value = (value << 4) + 10 + aChar - 'a';
						break;
					case 'A':
					case 'B':
					case 'C':
					case 'D':
					case 'E':
					case 'F':
						value = (value << 4) + 10 + aChar - 'A';
						break;
					default:
						throw new IllegalArgumentException(
								"Malformed   \\uxxxx   encoding.");
					}

				}
				outBuffer.append((char) value);
			} else {
				if (aChar == 't')
					aChar = '\t';
				else if (aChar == 'r')
					aChar = '\r';
				else if (aChar == 'n')
					aChar = '\n';
				else if (aChar == 'f')
					aChar = '\f';
				outBuffer.append(aChar);
			}
		} else
			outBuffer.append(aChar);
	}
	return outBuffer.toString();
}



你可能感兴趣的:(java,exception,android,String,null)