赞
踩
httpconn.getResponseCode()==HttpURLConnection.HTTP_OK异常
的简单处理办法
安卓升级后,不再允许目标 超过 API 8 的 通过运行, 估计就是为了改善
性能,让新硬件可以充分发挥优势.多开几个线程,不等等,还能处理其他的任务
解决方案就是
//A 位置 try{ URL url=new URL(wikiSearchURL); HttpURLConnection httpconn=(HttpURLConnection)url.openConnection(); //尽量简化,中国的超时,属性设置就不写了. if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK ){//错误位置 InputStreamReader inputStreamReader =new InputStreamReader (httpconn.getInputStream(), "utf-8"); int i; String content=""; // 读取消息到 content 中 while ((i = inputStreamReader.read()) != -1) { content = content + (char) i; } //位置F //位置 C //位置 D inputStreamReader.close(); } httpconn.disconnect(); }catch(IOException e){ e.printStackTrace(); } //B位置
以上就是错误的运行块
【下面开始 开新线程 运行出错的代码块】
下面的代码插入 A 位置
new Thread() { //线程
//==================================
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(wikiSearchURL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
//===========================================
@Override
public void run() {
}
}.start();
//==================================
//位置 E
//主线程中的handle用来接收子线程中的Message以便更新UI
上面的 插入B 位置
这样就完成了.开线性运行该网络连接.
不但是联网的代码需要在 开线程中,还有些, 更新
主UI 的方法,也不能直接使用,
下面就是如果将数据传递给主UI
代码尽量简化
下面的代码可以插入到 E 位置
handler=new Handler(){ //开一个句柄 给线程来发消息
@Override
public void handleMessage(Message msg) {
if (msg!=null){ //没有识别(需要补起来,简化 略....)
String content=(String)msg.obj;
// 将获取的内容显示到界面上
mShowWiki.setText(content);
}
super.handleMessage(msg);
}
};
下面的代码插入 C 和 D 之间
//==================================
//抛出消息到队列
// 子线程中的handle用来给主线程传递消息,
// 但是主线程中的handle也要等待该Message,否则不会继续,然后更新UI
Message msg = Message.obtain();
msg.obj = content;
handler.sendMessage(msg);
//==================================
程序片段中使用的几个 属性
private String wikiSearchURL="https://zh.wikipedia.org/w/api.php?action=opensearch&search=Android";
private TextView mShowWiki;
public Handler handler=null;
引入的几个包
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper; //之所以要引入 looper 是为了 Toast 方法
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
【运行条件】
1.运行程序, 使用 API 19 的手机,通过.
2.运行的wiki 网址. 需要翻墙访问.
3.上面代码要放在 主线程UI 的 onCreate () 中
下面是 运行 Toast 的方法
这个方法 放在,类其他方法一起,
//================================== //不能直接调用 Toast //================================== public void Toast_Looper (String toastString ) { final String toastStringMsg=toastString; new Thread() { @Override public void run() { super.run(); Looper.prepare(); try { Toast.makeText(getApplicationContext(), toastStringMsg, Toast.LENGTH_SHORT).show(); } catch (Exception e) { } Looper.loop(); } }.start(); } //==================================
插入嗲吗参考位置 F
Toast_Looper("完成读取");
//在这里插入代码片
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。