網絡獲取JSON相應代碼備份

項目中頻繁要用到網絡獲取JSON數據並且進行處理,我乾脆將代碼寫成一個類以後拿去用算了。

package com.example.luntan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.content.SharedPreferences;

public class JsonHandle {
	private static String sso;

	/**
	 * 獲取登錄信息
	 */
	private static void getSso(Context context) {
		SharedPreferences sp = context.getSharedPreferences("login", 0);
		sso = sp.getString("sso", "sso");
	}

	/**
	 * 獲得JSON的字符串數據
	 * 
	 * @param context
	 * @param api
	 * @return
	 */
	public static String getJsonString(Context context, String api) {
		getSso(context);

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(api);
		get.setHeader("Cookie", sso);
		try {
			HttpResponse response = client.execute(get);
			String result = inputStreamToString(
					response.getEntity().getContent()).toString();
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 把inputStream轉化爲StringBuilder
	 * 
	 * @param is
	 * @return
	 */
	private static StringBuilder inputStreamToString(InputStream is) {
		String line;

		StringBuilder total = new StringBuilder();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		try {
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return total;
	}

}



發佈了85 篇原創文章 · 獲贊 2 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章