2017-10-19 2 views
-2

Java를 통해 일부 URL에 액세스하려고합니다.java.net.URI의 java.lang.NullPointerException 오류

제 코드에서는 서버 인증을위한 자격 증명을 제공했습니다. 또한 서버에서 사용할 수있는 URL 목록 (xml 형식)을 추출하여 목록에있는 각 URL을 자동으로 호출 할 수있는 배열에 넣습니다. 나는 (URL을 받고) 문제가 코드의 마지막 부분에서 생각

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) 

:

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())); 
       } 
      } 
    } 
} 
} 

출력 오류는 다음과 같습니다

내 코드입니다. 나는 문제가 뭔지 모르겠다. 아무도 도와 줄 수 있습니까?

+2

디버거를 사용하고 null 포인터의 원인을 정확히 * 좁히십시오 – notyou

+0

ClientAuthentication.java의 85 줄은 무엇입니까? – Henry

답변

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

100 대신 nl.getLength을 사용하고 있습니까? 당신이 HttpGet을 실체화 나중에이 배열을 반복하기 때문에

은, 모든 마지막 세포되지 실체화는 여전히 null 있습니다 null 될 수 없습니다 매개 변수 beause 예외를 던지는 new HttpGet(array[i])로 이어지는.

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]); 

배열에 null이 남아있을 때까지 작동합니다.

배열을 new String[nl.getLength()]으로 설정하십시오. 지금부터는 더 이상 필요하지 않습니다. (이하).

+0

당신은 천재입니다! 이 문제를 해결해 주셔서 감사합니다! –

+1

@CassandraLehmann을 환영합니다. 디버거를 사용하는 법을 배워야합니다. 이 문제는 현지화하기가 복잡하지 않으므로 짧은 시간에 해결할 수 있습니다. – AxelH

+0

필자는 코딩을 언급했으며 디버거가 있는지 몰랐습니다. 하지만 지금은 확실히 살펴볼 것입니다. 다시 한 번 감사드립니다! –

관련 문제