android出现这个问题:
http://www.oschina.net/code/snippet_12_5909
private void dopost(String val){
//封装数据
Map<String, String> parmas = new HashMap<String, String>();
parmas.put("name", val);
DefaultHttpClient client = new DefaultHttpClient();//http客户端
HttpPost httpPost = new HttpPost("http://mhycoe.com/test/post.php");
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
if(parmas != null){
Set<String> keys = parmas.keySet();
for(Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String)i.next();
pairs.add(new BasicNameValuePair(key, parmas.get(key)));
}
}
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
/*
* 将POST数据放入HTTP请求
*/
httpPost.setEntity(p_entity);
/*
* 发出实际的HTTP POST请求
*/
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String returnConnection = convertStreamToString(content);
show.setText(returnConnection);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
解决方法,加权限!!
<uses-permission android:name="android.permission.INTERNET"/>
如果用接着出现异常android.os.NetworkOnMainThreadException:
参考
http://www.cnblogs.com/freexiaoyu/archive/2012/04/13/2445707.html
注意:造成这样的错误原因是代码不符合Android规范,如果把上面访问方式改为异步操作就不会出现在4.0上访问出现 android.os.NetworkOnMainThreadException异常
如:
new Thread(){
@Override
public void run(){
//你要执行的方法
//执行完毕后给handler发送一个空消息
handler.sendEmptyMessage(0);
}
}.start();
//定义Handler对象
private Handler handler =new Handler(){
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg){
super.handleMessage(msg);
//处理UI
}
};