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
.
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");
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With