我也是刚刚接触程序开发,一个菜鸟。前面和几个同学准备做一个移动教务系统,网上看了很多资料都说了对运行一些费时。如数据库、网络的链接操作,需要新开一个thread对其进行处理。但是后面在对程序进行调试的过程中,刚开始的时候报了空指针错误。根据错误提示,进行修改。说实话,经过那个过程发现自己真的还很菜,排错的经验太少了。直到过了好久才想到报了空指针错误,是因为在线程里生成的对象,因为有时间延迟,对于线程后面的对象来说是空的,所以才导致了空指针错误。后面参考的解决方法是利用join()函数。当然也可用其他方法。
下面写的代码:
public class MyThread extends Thread {
private InputStream is = null;
private String url;
private String method;
private List<NameValuePair> params;
public MyThread(String url, String method, List<NameValuePair> params) {
this.method = method;
this.url = url;
this.params = params;
}
public void run() {
try {
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
BasicHttpParams httpParameters = new BasicHttpParams();
// Set the default socket timeout (SO_TIMEOUT)
HttpConnectionParams
.setConnectionTimeout(httpParameters, 30000);
// in milliseconds which is the timeout for waiting for
// data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
setIs(httpEntity.getContent());
} else if (method.equals("GET")) {
BasicHttpParams httpParameters = new BasicHttpParams();
// Set the default socket timeout (SO_TIMEOUT)
HttpConnectionParams
.setConnectionTimeout(httpParameters, 30000);
// in milliseconds which is the timeout for waiting for
// data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
String temp_url = url + "?" + paramString;
HttpGet httpGet = new HttpGet(temp_url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
setIs(httpEntity.getContent());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
}
通过下面的语句对以上生成的对象(“setIs(httpEntity.getContent());
“)进行调用
MyThread myThread = new MyThread(url, method, params);
myThread.start();
myThread.join();//同做join()函数对myThread进行处理,使其一般的对象那样使用即可
is = myThread.getIs();//获得is对象
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。