2017-10-19 30 views
-2

J'essaie d'accéder à certaines URL via Java.java.lang.NullPointerException à java.net.URI erreur

Dans mon code, j'ai fourni des informations d'identification pour l'authentification du serveur. J'ai également extrait une liste (au format xml) des URL disponibles sur le serveur et les ai placées dans un tableau où je peux appeler chacune des URL de la liste automatiquement.

Ceci est mon code:

import java.io.File; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.CredentialsProvider; 
import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.BasicCredentialsProvider; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.util.EntityUtils; 
import java.io.FileOutputStream; 
import java.lang.reflect.Array; 
import org.apache.http.HttpEntity; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathConstants; 
import javax.xml.xpath.XPathExpression; 
import javax.xml.xpath.XPathFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 
import org.w3c.dom.Node; 

public class ClientAuthentication { 

public static void main(String[] args) throws Exception { 
    /*CREATING FILE*/ 
    File myFile = new File("C:/input.xml"); 

    /*DEFINING CREDENTIALS*/ 
    CredentialsProvider credsProvider = new BasicCredentialsProvider(); 
    credsProvider.setCredentials(new AuthScope("localhost", 80),new UsernamePasswordCredentials(" ", " ")); 

    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){ 
     HttpGet httpget = new HttpGet("http://localhost/app/rest/buildTypes"); 
     /*WRITE TO FILE*/ 
     try (CloseableHttpResponse response = httpclient.execute(new HttpGet("http://localhost/app/rest/buildTypes"))){ 
      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       try (FileOutputStream outstream = new FileOutputStream(myFile)) { 
       entity.writeTo(outstream); 
       } 
      } 
     } 

     /*SHOW EXECUTION*/ 
     System.out.println("Executing request " + httpget.getRequestLine()); 
     try (CloseableHttpResponse response = httpclient.execute(httpget)) { 
      System.out.println("----------------------------------------"); 
      System.out.println(response.getStatusLine()); 
      System.out.println(EntityUtils.toString(response.getEntity())); 
     } 
    } 

    /*Extract all Build ID from XML file*/ 
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document doc = builder.parse("C:/input.xml"); 
    XPathFactory xPathfactory = XPathFactory.newInstance(); 
    XPath xpath = xPathfactory.newXPath(); 
    XPathExpression expr = xpath.compile("//buildTypes/buildType[@id]"); 
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); 

    /*Creating url and saving into array*/ 
    String array[] = new String[100]; 
    for (int i = 0; i < nl.getLength(); i++){ 
     Node currentItem = nl.item(i); 
     String key = currentItem.getAttributes().getNamedItem("id").getNodeValue(); 
     String pathing = "http://localhost/app/rest/" + (key); 
     System.out.println(pathing); 
     array[i] = pathing; 
    } 

    /*Getting the url*/ 
    int size = Array.getLength(array); 
    for (int i = 0; i < size; i++){ 
     try (CloseableHttpClient areq = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){ 
       HttpGet httpget = new HttpGet(array[i]); 

       /*SHOW EXECUTION*/ 
       System.out.println("Executing request " + httpget.getRequestLine()); 
       try (CloseableHttpResponse response = areq.execute(httpget)) { 
        System.out.println("----------------------------------------"); 
        System.out.println(response.getStatusLine()); 
        System.out.println(EntityUtils.toString(response.getEntity())); 
       } 
      } 
    } 
} 
} 

L'erreur de sortie est:

Exception in thread "main" java.lang.NullPointerException 
    at java.net.URI$Parser.parse(URI.java:3042) 
    at java.net.URI.<init>(URI.java:588) 
    at java.net.URI.create(URI.java:850) 
    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:66) 
    at ClientAuthentication.main(ClientAuthentication.java:85) 
Java returned: 1 BUILD FAILED (total time: 0 seconds) 

Je pense que le problème est au cours des dernières parties du code (obtenir l'URL). Je ne sais pas quel est le problème. quelqu'un peut-il aider s'il vous plait?

+2

Utilisez un débogueur et affinez * à * exactement la cause du pointeur nul – notyou

+0

Qu'est-ce que la ligne 85 dans ClientAuthentication.java? – Henry

Répondre

0
String array[] = new String[100]; 
for (int i = 0; i < nl.getLength(); i++){ 
    ... 

Pourquoi utilisez-vous 100 au lieu de nl.getLength?

Puisque vous itérer ce tableau plus tard à instancier HttpGet, toutes les dernières cellules non instancier sont encore null, conduisant à new HttpGet(array[i]) lancer une exception beause le paramètre ne peut pas être null.

int size = Array.getLength(array); 
for (int i = 0; i < size; i++){ 
    try (CloseableHttpClient areq = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build()){ 
      HttpGet httpget = new HttpGet(array[i]); 

Cette volonté fonctionne jusqu'à la null restant dans votre tableau.

Instanciez votre tableau avec new String[nl.getLength()]. Puisque vous n'avez plus besoin de rien maintenant. (ou moins).

+0

Vous êtes un génie! Merci cela a réglé le problème! –

+1

Vous êtes les bienvenus @CassandraLehmann. Vous devriez apprendre à utiliser un débogueur. Ce problème n'est pas compliqué à localiser, donc vous auriez pu le réparer vous-même dans un court laps de temps. – AxelH

+0

Je viens d'indiquer le codage et je ne savais pas qu'il y avait un débogueur. Mais je vais certainement le regarder maintenant. Merci encore! –