我有这个功能,它执行网络操作..(即将数据发布到网页中)..但我得到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