【发布时间】:2015-12-25 03:44:58
【问题描述】:
您好,我想知道是否有人可以帮助我解决以下问题,我有一个当前已填充的数据库。我曾经使用 http 客户端调用它,它运行良好,但现在我正在尝试更新代码,因为它已被弃用以使用 httpurlconnection,但我没有成功。我查阅了一些教程并尝试了一些东西,但似乎没有用。数据库通过 php 文件调用并以 json 格式返回。如果我要从浏览器调用 php 文件,则响应如下: [{"id":"15","logo":"logo url ","title":"title"}]
我在控制台上得到的错误如下:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
这对我来说没有多大意义,因为脚本会提取信息
我有以下代码,我留下了注释部分以防万一我需要它,它还包括我用来调用数据库的旧方式谢谢!:
公共无效负载新闻(){ InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
【问题讨论】:
-
您正在打开
InputStream in.. 但您正在关闭is.close();。哎呀:) -
做到了!哈哈流行是对的,总是那些小东西我应该把它放在哪里?
标签: java php android httpurlconnection