android 獲取web 內容簡單實現

一種是HttpURLConnection 方法: php

public String connect() throws IOException{
		URL url;

		url = new URL("http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json");
	
		// 每一個HttpURLConnection實例均可用於生成單個請求,可是其餘實例能夠透明地共享鏈接到 HTTP 服務器的基礎網絡

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		
		//設置URL請求的方法 
		conn.setRequestMethod("GET"); 
	
		//設置一個指定的超時值(以毫秒爲單位),該值將在打開到此 URLConnection 引用的資源的通訊連接時使用。

		conn.setConnectTimeout(5 * 1000); 

		//conn.getInputStream()返回今後打開的鏈接讀取的輸入流 
		InputStream in=conn.getInputStream();
		System.out.println(in.available());
		ByteArrayOutputStream bout=new ByteArrayOutputStream();
		int c;
		while((c=in.read())!=-1){
			bout.write(c);
		}
		byte b[]=bout.toByteArray();
		
		in.close();
		bout.close();
		
		return new String(b);
		


	}
另外一種是apache的HttpClient包中的方法:

HttpClient client=new DefaultHttpClient();
		//POST url
		String posturl="http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json";
		//創建HttpPost對象
		HttpPost httpPost=new HttpPost(posturl);
		//創建一個NameValuePair數組,用於存儲欲傳遞的參數
		List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
		//添加參數
		params.add(new BasicNameValuePair("user", "1"));
		
		//設置編碼
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//發送Post,並返回一個HttpResponse對象  
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
相關文章
相關標籤/搜索