Android HTTP URL connection shows null pointer exception
In my Android application, I have to download XML files from the server. I used the code that shown below. Sometimes it shows null pointer exception for getResponseCode() method. the httpConn is not null.
public static byte[] get开发者_StackOverflow中文版GprsConnData(String urlStr){
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if(!(urlConn instanceof HttpURLConnection)){
Log.e("Error", "connection is not an instance of HTTP connection");
throw new IOException ("URL is not an Http URL");
}
httpConn = (HttpURLConnection)urlConn;
if(httpConn == null){
System.out.println("httpconnection is null");
}else{
System.out.println("httpconnection isn't null");
}
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
System.out.println("getting http Connection ");
httpConn.connect();
System.out.println("http Connection established");
int code = -1;
try{
code = httpConn.getResponseCode();
}catch(Exception e){
e.printStackTrace();
Log.e("Exception", "while getting http response code");
}
System.out.println("http Connection response code" + code);
if(httpConn != null && httpConn.getResponseCode()!= HttpURLConnection.HTTP_OK){
return null;
}
System.out.println("getting inputStream");
InputStream fromServer = httpConn.getInputStream();}
What would be the reason for that exception?
精彩评论