I wrote a little programm, that reads an XML-File via http-get.
Loacally it's running fine.
But on the server it keeps breaking without any exception, except a nullpointer because of the empty result
I'm using the apache http lib.
Here is the class, i added the numbers, to track the exact point, where it stops working.
public void get(String url, String user, String pass, File outfile) throws IOException
{
log.info("1");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials(user, pass));
log.info("2");
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
HttpResponse response = null;
log.info("6");
InputStream content = null;
FileOutputStream outputStream = null;
try
{
HttpGet httpGet = new HttpGet(url);
log.info("3");
httpGet.addHeader("Content-Type", "text/xml");
log.info("4");
httpGet.addHeader("Accept", "text/xml");
log.info("5");
log.info("6");
log.info("7");
outputStream = new FileOutputStream(outfile);
log.info("8");
response = httpClient.execute(httpGet);
log.info("9");
log.info("response: {}", response);
log.info("10");
content = response.getEntity().getContent();
log.info("11");
log.info("content: {}", content);
log.info("12");
IOUtils.copy(content, outputStream);
log.info("13");
}
catch (Exception e)
{
log.error("", e);
}
finally
{
try
{
log.info("14");
log.info(String.valueOf(content));
content.close();
outputStream.close();
}
catch (IOException e)
{
log.error("Error while closing Streams", e);
}
}
}
Here are the log snipets; I tried to mask every sensible data and i hope i didn't miss anything
Local log snipet
Remote log snipet
As you can see, the numbers stop after 8 and start in the finally block again with 14. the rest is missing and I have no idea, why.
The used URL is reachable via browser or comandline.
The problem is a bit tricky: you are running into some sort of Error here. Probably NoClassDefFoundError or something alike.
But as you are catching for Exception this piece of code simply doesn't "see" the real problem.
So to debug the problem: either check the server log files or change your code to catch Throwable instead of Exception.
Related
I write application which must show page content(text and images) via url-request. My task requires to do it manually, for example variant such as WebView webView.loadUrl(url.toString()); is not suitable. How to solve this task in another way?
Try using HTTPClient. something like this.
public static InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.("[GET REQUEST]", "Network exception", e);
}
return content; //url content is here.
}
I am trying to authenticate to a Windows server running IIS that is configured for Windows Integrated Authentication (SPNEGO) using Apache HttpClient 4.3. My code looks very similar to that of the sample code I've been able to locate online, but when I run it I consistently get an HTTP 401 returned. I ran Wireshark on the results, and do not see the SPNEGO token being passed on to the server.
I'm able to hit the protected resource just fine via a web browser, and in this case I do see the SPNEGO token. The behavior is different when I run my code, though. Here is the code in question:
public static void main(String[] args) {
System.setProperty("java.security.krb5.conf",
"c:\\develop\\XYZ\\KerberosTest\\conf\\krb5.conf");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
System.setProperty("java.security.auth.login.config",
"c:\\develop\\XYZ\\KerberosTest\\conf\\login.conf");
Credentials jaasCredentials = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(null, -1, null),
jaasCredentials);
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder
.<AuthSchemeProvider> create().register(AuthSchemes.SPNEGO,
new SPNegoSchemeFactory()).build();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultAuthSchemeRegistry(authSchemeRegistry)
.setDefaultCredentialsProvider(credsProvider).build();
try {
HttpGet httpget = new HttpGet(ENDPOINT);
RequestLine requestLine = httpget.getRequestLine();
CloseableHttpResponse response = httpclient.execute(httpget);
try {
StatusLine status = response.getStatusLine();
HttpEntity entity = response.getEntity();
if (entity != null) {
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I believe I have configured my krb5.conf file correctly, and my login.conf file is taken directly from the Apache HttpClient documentation. I've also made the appropriate registry key change, as mentioned in the docs.
Any idea what could be causing this or how I could go about troubleshooting? Is there a step or line I am missing?
Problem solved. This appears to be due to a bug in IBM's JDK. Once I changed to Sun's, everything works.
I use the following code and run the method multiple times, a few times I get a response in GZIP which is what I expect and a few other times I get a response that is completely different(non GZIP page not found). However if I download the same URL multiple times using Mozilla or IE I consistently get the same GZIP response.
Is this an error with the server I am trying to reach to, or do I need to set any parameters to get a consistent response ?
The URL I am trying to download is the following, can you please let me know ?
public static byte[] dowloadURL(URL urlToDownload) {
InputStream iStream = null;
byte[] urlBytes = null;
try {
//HttpClient httpClient = new HttpClient();
org.apache.http.client.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urlToDownload.toString());
HttpResponse response = httpClient.execute(httpget);
iStream = response.getEntity().getContent();
urlBytes = IOUtils.toByteArray(iStream);
String responseString = new String(urlBytes);
System.out.println(" >>> The response string for " +urlToDownload.toString()+ " is " +responseString);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s: %s",
urlToDownload.toExternalForm(), e.getMessage());
e.printStackTrace();
// Perform any other exception handling that's appropriate.
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return urlBytes;
}
am trying to get the XML file from a URL but am getting no Response and the code stops later because the String xml is null, can you tell me whats the problem ?
public String getXmlFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
return xml;
} catch (Exception e) {
e.printStackTrace();
}
Please be specific in you answers I appreciate your help
Why you are using HTTPPost?? You are not sending any data Even. Try with HttpGet.
Try This :
public String getXmlFromUrl(String url) throws Exception {
return new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
Log.i("DEMO", xml);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
}.execute(url).get();
}
Try to start your code from separate thread e.g.
new Thread(new Runnable()
{
#Override
public void run()
{
// TODO your code here
}
}).start();
try this:
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
for geturldata()
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}
You should understand Exceptions. The reason xml is null is because 'something' went wrong. This threw an Exception, probably with a good description of what went wrong. When this happens, the Exception is thrown 'up' until someone handles it.
Every subclass of Exception has a different 'flavor' and is thrown in specific cases. This enables you to 'react' on errors. For instance, you could tell the user what went wrong, or log something for debugging sake.
In your case, you 'catch' all exceptions in a single place, when an exception occurs, the code after catch (Exception e) is executed. You do nothing here but printing out some stuff (this will appear orange in your LogCat). Then you continue as if nothing happened. But xml will be null, which is bad for your program, and you apparently didn't notice the LogCat entry because your program crashes at a later point.
This time, Eldhose M Babu solved your problem. Next time, when something else goes wrong (and a lot can go wrong in htttp requests), your program will show the same behavior. Try and read up on exceptions and be careful when you handle them too silently.
Getting exception near DefaultHttpClient when i am trying to access restful wcf service in java.Here is my code:
public String rest(String SERVICE_URI){
String a="";
try{
HttpGet request = new HttpGet(SERVICE_URI + "/hello");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
**DefaultHttpClient httpClient = new DefaultHttpClient();**
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONArray plates = new JSONArray(new String(buffer));
a=plates.toString();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
}
the exception is :
Exception in thread "main" java.lang.VerifyError: (class:
org/apache/http/impl/client/DefaultHttpClient,
method: createHttpParams signature:
()Lorg/apache/http/params/HttpParams;)
Incompatible argument to function
Please can anyone help me ...Thank you.
This seems to be a class loader problem. Your code is probably compiled against one jar file (containing the HTTP client stuff). But when it's run, a different, incompatible jar file with the same class is used.
Are you running the code within an application server? If yes, the application server might already have a different version of the Apache Http client libraries in a shared location that takes precedence.
I would guess that your problem might be related to the fact that you are setting a Content-Type header for a GET. GET requests should not include Content-Type headers.