android 發送http請求
阿新 • • 發佈:2017-07-20
ans xxx pub 輸入 項目 建立 run 第一行代碼 pack
代碼是沒有問題的,但是app端發送請求。server端卻一直沒有信息打印。
好久沒寫博客了,由於公司要做android,筆者也是第一次接觸。
這是在項目中遇到一個比較麻煩的問題。記錄下來備忘(本人剛接觸。有不正確的地方請不吝賜教)。
發送請求的代碼:
package com.jiujian.mperdiem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class AppUtil { // 本地測試路徑 public static final String webBaseUrl = "http://ip:端口"; /* * 訪問URL。獲取結果 method: GET, POST */ public static String loadUrlResponse(String method, String urlString) { HttpURLConnection conn = null; // 連接對象 InputStream is = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(urlString); // URL對象 conn = (HttpURLConnection) url.openConnection(); // 使用URL打開一個鏈接 conn.setDoInput(true); // 同意輸入流,即同意下載 conn.setDoOutput(true); // 同意輸出流,即同意上傳 conn.setUseCaches(false); // 不使用緩沖 conn.setRequestMethod(method); // 使用get請求 is = conn.getInputStream(); // 獲取輸入流。此時才真正建立鏈接 InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { result.append(inputLine).append("\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } } return result.toString(); } }
調用代碼:
StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl); sbUpdateDeviceRefreshInstall.append("XXX?UserId="); sbUpdateDeviceRefreshInstall.append(getUserId()); AppUtil.loadUrlResponse("POST", sbUpdateDeviceRefreshInstall.toString());
代碼是沒有問題的,但是app端發送請求。server端卻一直沒有信息打印。
錯誤信息是:android.os.NetworkOnMainThreadException
最後才發現android 3.0以後就不同意在主線程上進行網絡訪問的,
於是把代碼改成:
new Thread(){ @Override public void run() { StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl); sbUpdateDeviceRefreshInstall.append("XXX?UserId="<span style="font-family: 'Microsoft YaHei';">);</span> sbUpdateDeviceRefreshInstall.append(getUserId()); AppUtil.loadUrlResponse("POST", sbUpdateDeviceRefreshInstall.toString()); } }.start();
這樣就沒問題了。
假設是剛接觸android,能夠推薦看:第一行代碼,這本書對於入門來說挺不錯的。
個人主頁:http://www.itit123.cn/ 很多其它幹貨等你來拿
android 發送http請求