用于解析Json数据的HttpUtils工具类

该工具类用于解析网址中的Json数据

package org.mobiletrain.robot.http;

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.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.mobiletrain.robot.bean.ChatMessage;
import org.mobiletrain.robot.bean.ChatMessage.Type;
import org.mobiletrain.robot.bean.Result;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.R.string;

/**
 * 联网工具类,用于连接网络,取得数据
 *
 */

public class HttpUtils {
	// 图灵机器人使用api的公网地址
	public static final String URL = "http://www.tuling123.com/openapi/api";
	// 申请的apiKey
	public static final String API_KEY = "be12dd3c0bac3654e78aa69e4b36a6dd";
	
	/**
	 * 通过HttpURLConnection解析Json数据,返回结果是一个字符串
	 * @param url
	 * @return
	 */
	public static String getJsonContent(String url) {
		String result = "";
		URL url2;
		InputStream is;
		InputStreamReader isr;
		BufferedReader br;
		try {
			url2 = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) url2
					.openConnection();
			is = connection.getInputStream();
			isr = new InputStreamReader(is, "utf-8");
			String line = "";
			br = new BufferedReader(isr);
			while ((line = br.readLine()) != null) {
				result += line;
			}
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 通过HttpClient解析Json数据,返回结果是一个字符串
	 * @param url
	 * @return
	 */
	public static String getJsonContent2(String url) {
		String result = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 解析Json数据,返回结果是一个byte[]数组,一般用于解析网络图片
	 * @param url
	 * @return
	 */
	public static byte[] getByteContent2(String url) {
		byte[] data = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				data = EntityUtils.toByteArray(response.getEntity());
			}
			return data;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return data;

	}
	/**
	 * 通过HttpURLConnection解析Json数据,返回结果也是一个byte[]类型的数组
	 * @param url
	 * @return
	 */
	public static byte[] getByteContent(String url) {
		try {
			URL url2 = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) url2
					.openConnection();
			httpConn.setDoInput(true); // 允许输入内容
			httpConn.setDoOutput(false);
			httpConn.connect();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			if (httpConn.getResponseCode() == 200) {
				BufferedInputStream bis = new BufferedInputStream(
						httpConn.getInputStream());
				byte[] buffer = new byte[8 * 1024];
				int c = 0;
				while ((c = bis.read(buffer)) != -1) {
					baos.write(buffer, 0, c);
					baos.flush();
				}
				byte[] data = baos.toByteArray();
				return data;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 拼接接口,其中参数为用户输入传来的内容
	 */
	public static String setParams(String msg){
		String url = "";
		try {
			 url = URL +"?key="+API_KEY+"&info="+URLEncoder.encode(msg, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	
	/**
	 * 解析Json数据,返回类型是一个ChatMessage对象
	 * @param msg
	 * @return
	 */
	public static ChatMessage sendMessage(String msg){
		ChatMessage chatMessage = new ChatMessage();
		String jsonRes = getJsonContent(setParams(msg));
		Gson gson = new Gson();
		Result result = null;
		try {
			result = gson.fromJson(jsonRes, Result.class);
			chatMessage.setMessage(result.getText());
		} catch (JsonSyntaxException e) {
			chatMessage.setMessage("服务器繁忙,请稍后再试");
		}
		chatMessage.setDate(new Date());
		chatMessage.setType(Type.INCOMING);
		return chatMessage;
	}
}


你可能感兴趣的:(android,json,网络,数据)