我有這個功能,它執行網絡操作..(即將數據發佈到網頁中)..但我得到android.os.NetworkOnMainThreadException ..我知道我必須使用android.os.NetworkOnMainThreadException在網絡上的線程操作,但我不知道該怎麼做......難道u人請幫我看看我的代碼..提前 感謝..... 這裏是我的方法如何使用線程進行聯機操作
public static String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
String g=e.toString();
Log.d("errererer", g);
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
可以使用的AsyncTask了點。檢查此鏈接http://developer.android.com/intl/zh-tw/reference/android/os/AsyncTask.html – DarwinLouis