今天想在Android下,用httpClient去获取网页的内容,结果在httpClient处报了错,
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145), libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84), libcore.io.IoBridge.connectErrno(IoBridge.java:127), libcore.io.IoBridge.connect(IoBridge.java:112), java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192), java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459), java.net.Socket.connect(Socket.java:843), org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119), org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144), org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164), org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119), org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360), org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555), org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpCl
问我们的Android大神,得知Android不能再主线程去访问网络,需要另起线程去访问
方法一:
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public static String getHtmlByUrl(String url){
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
在httpClient访问前,加上红颜色的代码。
方法二:
用java创建个线程,在线程中去httpClient访问网络。