Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 發送http請求實例

Android 發送http請求實例

編輯:關於Android編程

           		URL url;
			try {
				OutputStream os = null;
				
				url = new URL(uri);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setRequestMethod("POST");

				conn.setFixedLengthStreamingMode(packetData.length);
				conn.setUseCaches(false);
				
				
				os = conn.getOutputStream();
				int offset = 0;
				int len = READ_WRITE_SIZE;

				while (offset < packetData.length){
					if (offset + len > packetData.length){
						len = packetData.length - offset;
					}
					os.write(packetData, offset, len);
					os.flush();
					offset += len;
				}
				InputStream fin = null;
				fin = conn.getInputStream();
				BufferedReader r = new BufferedReader(new InputStreamReader(fin)); 
				StringBuilder total = new StringBuilder(); 
				String line; 
				while ((line = r.readLine()) != null) { 
				    total.append(line); 
				}

				tv.setText("---> "+total);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

需要注意的是不能在主線中進行http請求,需要

new Thread(mRun).start();  
Runnable mRun = new Runnable(){}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved