嗨,我有一个问题,我从Google URL中创建JSON文件。这是我使用的代码。
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadUrl {
public String readUrl(String strUrl) throws IOException, InterruptedException {
Log.d("URLS = ",strUrl);
Thread.sleep(2000);
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
当我将看起来像这样的URL扔进其中时,它可以正常工作。https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7207523,-73.383851& amp;radius = 4828&
但是,当我尝试将看起来像这样的URL扔进其中时。https://maps.googleapis.com/maps/api/place/details/json?placeId=chije3amogsr6ikruwck1lah-de& amp; amkey = mykey
我有一个错误:d/googleplacesReadTask:java.lang.nullpointerexception:尝试调用虚拟方法'void java.io.inputstream.close.close.close()'null对象引用
我不知道我如何解决。有帮助吗?
aah您没有提到这是在Android中,我想这是因为你说,android.os.netWorkonMainThreadException在您的评论中
Android不允许在主线程上耗时的任务,使用asynctask调用您的功能或使用普通的旧Java线程
主线程异常上的网络会在主线程上运行网络操作时。通常,这些作品都使用异步,但是如果您想使用编写的相同代码,请添加。
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);