Android初識-通過URL地址請求並返回JSON數據

<pre name="code" class="java"><span style="font-size:18px;"><strong>通過POST方式請求URL並傳入參數並獲取返回值</strong></span>





/**
	 * 調用接口
	 * @param wsurl
	 * @param Parameters
	 * @return
	 */
	public static String RequestUrl(String wsurl,String Parameters)
	{
		String rvalue = "";
		try {
			//聲明URL
			URL url = new URL(wsurl);
			//打開連接
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			//設置連接方式
			conn.setRequestMethod("POST");
			//設置是否輸入參數
			conn.setDoOutput(true);
			//輸入參數
			conn.getOutputStream().write(Parameters.getBytes());
			//獲取返回值
			InputStream inStream = conn.getInputStream();
			//流轉化爲字符串
			rvalue = StreamTools.streamToStr(inStream);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rvalue;
	}

過GET方式請求URL並獲取返回值

HttpURLConnection connection = null;
		Reader read;
		BufferedReader bufferReader;
		try {
			URL url = new URL(weatherurl);
			connection = (HttpURLConnection) url.openConnection();
			
			connection.setConnectTimeout(8000);
			connection.setRequestMethod("GET");
			connection.setReadTimeout(8000);
			InputStream in = connection.getInputStream();
			獲取讀取的方式
			read=new InputStreamReader(connection.getInputStream());
			bufferReader=new BufferedReader(read);
			
			//獲取服務器返回的字符串
			String str;//讀取每一行數據
			StringBuffer buffer=new StringBuffer();//接受全部數據
			while((str=bufferReader.readLine())!=null){
				buffer.append(str + "\n");
			}
			
			//關閉連接
			read.close();  
			connection.disconnect();
			
			//測試	
			Log.d("發出去的請求",weatherurl.toString());
			Log.d("讀取來的數據",buffer.toString());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}

HttpClient請求URL並獲取返回值

<pre name="code" class="java">HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(weatherurl);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String jsonString = EntityUtils.toString(
						httpResponse.getEntity(), "utf-8");
}



package com.example.pagedemo.utils;

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

public class StreamTools {

	/**
	 * 把流對象轉換成字符串對象
	 * 
	 * @param is
	 * @return
	 */
	public static String streamToStr(InputStream is) {
		try {
			// 定義字節數組輸出流對象
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			// 定義讀取的長度
			int len = 0;
			// 定義讀取的緩衝區
			byte buffer[] = new byte[1024];
			// 按照定義的緩衝區進行循環讀取,直到讀取完畢爲止
			while ((len = is.read(buffer)) != -1) {
				// 根據讀取的長度寫入到字節數組輸出流對象中
				os.write(buffer, 0, len);
			}
			// 關閉流
			is.close();
			os.close();
			// 把讀取的字節數組輸出流對象轉換成字節數組
			byte data[] = os.toByteArray();
			// 按照指定的編碼進行轉換成字符串(此編碼要與服務端的編碼一致就不會出現亂碼問題了,android默認的編碼爲UTF-8)
			return new String(data, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String streamToString(InputStream is)
	{
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
			
			StringBuilder sb = new StringBuilder();
			
			String line;
			while((line = reader.readLine()) != null)
			{
				sb.append(line);
			}
			return sb.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章