I would like to download and parse a Mapbox PBF file from the web using Java. If I download the file manually, I am able to parse it without any errors. However, if I use Java code to download the file, and then try to parse the downloaded file, I get the following Exception:
Exception in thread "main"
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:111)
By Googling this error, some people are saying the file is corrupt.
Is there something I am missing when trying to write this kind of binary data to file programmatically?
Here's some code showing two ways I am trying to download the file:
Technique 1
fileURL = "https://api.mapbox.com/v4/mapbox.mapbox-traffic-v1/17/36159/54906.vector.pbf?style=mapbox://styles/fnembhard/ck9inh9df002c1jpnccjg20pw@00&access_token=..."
public void saveFile1(String fileURL, String fileName){
try{
URL testURL = new URL(fileURL);
if(testURL.getHost() != null) {
InputStream in = new URL(fileURL).openStream();
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
}
catch(Exception e){
e.printStackTrace();
}
}
Technique 2
public void saveFile2(String fileURL, String fileName){
try {
URL testURL = new URL(fileURL);
if (testURL.getHost() != null) {
InputStream in = new URL(fileURL).openStream();
// File f = new URL(fileURL).getFile();
OutputStream outputStream = new FileOutputStream(fileName);
int byteRead;
while ((byteRead = in.read()) != -1) {
outputStream.write(byteRead);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}