Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML String from URL in Java

Tags:

java

rest

url

null

xml

I am retrieving data from restful web service in XML format, but unfortunately my String is null. Please help me, where is the problem in my code?

Here is the example code:

URL url = new URL("http://loxvo.fogbugz.com/api.asp?cmd=logon&email=myemail&password=mypwd");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
InputStream is = request1.getInputStream();
BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
String responseData = IOUtils.toString(bf_reader);
System.out.print(responseData);

I have tried this url in rest client: it's returning me correct xml, but here my String is null.

like image 784
Junaid Akhtar Avatar asked Feb 14 '23 10:02

Junaid Akhtar


2 Answers

You can read response like

 BufferedReader bufferedReader = 
     new BufferedReader(new InputStreamReader(request1.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
          System.out.print(line);
        }

Getting resp 302 your code. Try with

 URL url = new URL("https://loxvo.fogbugz.com/api.asp?cmd=logon&email=myemail&password=mypwd");
like image 62
vels4j Avatar answered Feb 17 '23 03:02

vels4j


Try to just pass the InputStream of the request directly to IOUtils.toString( ), because IOUtils.toString makes buffering on its own.

Additionally you can check with request1.getResponseCode() if the request was successfull or if there was any kind of Http Error.

Furthermore it is not necessary to invoke the connect() method because this is implicitely done within the getInputStream() call.

Update: Getting also Error 302. Of course i d'ont have the correct login data. But the request must work using the following code:

try {
   URL url = new URL("http://loxvo.fogbugz.com/api.asp?cmd=logon&email=myemail&   password=mypwd");
   //URL url = new URL("http://www.google.de");
   HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
   request1.setRequestMethod("GET");
   // request1.connect();
   String code = String.valueOf(request1.getResponseCode());
   System.out.println("Error code "+code);
   InputStream is = request1.getInputStream();

   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
   String line;
   while ((line = bufferedReader.readLine()) != null) {
     System.out.println(line);
   }
   // BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
   // String responseData = IOUtils.toString(bf_reader);
   // System.out.print(responseData);
} catch (Exception e) {
    e.printStackTrace();
}
like image 35
Diversity Avatar answered Feb 17 '23 02:02

Diversity