I'm have the following code which I seem to be experiencing random image reading failure with with no exceptions. I'm running the following image url in a batch job, some of the other urls work some don't. The failure is ImageIO.read is null although it's a perfectly good working url. The url posted is the one I was experiencing the failure with. Anybody know what might be causing this code to fail.
I'd also like to say I'm using Java 8 as well.
try {
URL url;
url = new URL("https://content.homenetiol.com/672/27185/640x480/4d352f4ff9cf4948a93612e91401e128.jpg");
BufferedImage sourceImg = ImageIO.read(url);
System.out.println(sourceImg);
} catch (MalformedURLException ex) {
System.out.println("MalformedURLException " + ex.getMessage());
} catch (IOException ex) {
System.out.println("IOException " + ex.getMessage());
}
also a working url
https://content.homenetiol.com/672/27185/640x480/49a9236f2196432db81e477fde44e756.jpg
I'm pretty sure from mucking around with curl that the server occasionally responds with 302 redirect response that the standard Java URL doesn't handle.
Here is some code that uses Apache HttpClient to fetch the image, and works even when the server responds with a 302 redirect:
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet("https://content.homenetiol.com/672/27185/640x480/4d352f4ff9cf4948a93612e91401e128.jpg");
try (CloseableHttpResponse response = httpclient.execute(httpget);
InputStream stream = response.getEntity().getContent()) {
BufferedImage sourceImg = ImageIO.read(stream);
System.out.println(sourceImg);
}
} catch (IOException e) {
e.printStackTrace();
}
Related
In my Xpages application I am calling an external service to collect data.
Users are complaining that they sometimes get a timeout error message:
Connect to customerbank.acme.se:20543 [customerbank.acme.se/127.17.27.172] failed: Connection timed out: connect
I assumed the timeout would result in an IOException but apparently not. How can I catch this error?
Below is part of my code. The logic of handling the response I have left out.
private CloseableHttpClient httpclient;
try{
HttpClientBuilder cb = HttpClientBuilder.create();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30 * 1000)
.setConnectTimeout(30 * 1000)
.setConnectionRequestTimeout(30 * 1000)
.build();
cb.setDefaultRequestConfig(requestConfig);
httpclient = cb.build();
HttpPost httpPost = new HttpPost(urlFromConfiguration);
httpPost.setHeader("Content-Type", "application/json");
HttpEntity entity;
entity = new ByteArrayEntity(JSONobj.toString().getBytes("UTF-8"));
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
if (200 == response.getStatusLine().getStatusCode()){//response received
//perform some logic with the response...
}
} catch (IOException e) {
OpenLogUtil.logError(e);
FacesContext.getCurrentInstance().addMessage(null, new javax.faces.application.FacesMessage(javax.faces.application.FacesMessage.SEVERITY_ERROR, "some IO exception occurred", ""));
} catch (Exception e) {
OpenLogUtil.logError(e);
FacesContext.getCurrentInstance().addMessage(null, new javax.faces.application.FacesMessage(javax.faces.application.FacesMessage.SEVERITY_ERROR, "some general error has occured" , ""));
}
I think this Baeldung page can help you:
"Note that the connection timeout will result in an
org.apache.http.conn.ConnectTimeoutException being thrown, while
socket timeout will result in a java.net.SocketTimeoutException."
Apache Http client that you are using is a great utility. But it could be a bit heavy and cumbersome for a relatively simple task that you are running. There is a much simpler Http client provided in MgntUtils Open source library (written by me). It may be not as comprehensive as Apache one, but is much simpler in use. It does throw IOException upon connection or time-out error. In your case it could be an alternative to use. Take a look at Javadoc. Library itself provided as Maven artifacts and on Git (including source code and Javadoc). All in all your code may look like this:
private static void testHttpClient() {
HttpClient client = new HttpClient();
client.setContentType("application/json");
String content = null;
try {
content = client.sendHttpRequest("http://yourUrl.com", HttpMethod.POST, JSONobj.toString());
//content holds the response. Do your logic here
} catch (IOException e) {
//Error Handling is here
content = TextUtils.getStacktrace(e, false);
}
}
I'm developing an android app which connects to backend server via HTTPS. Everything is working properly when I use mobile data - no errors and other similar things. However, when I turn on WiFi and try to get some data from backend server I'm getting large delays (even 40 seconds) although I download just two lines of text, for example. I've also noticed that if I connect to backend server via HTTP, there is no problem using both mobile data and WiFi. I have tested many times if I set up SSL protocol properly and everything seems to be done properly.
I'm providing to you a piece of code, which is responsible for connecting with backend server from the app:
private boolean downloadData() {
try {
URI uri = new URI("https://www.example.com/resources/script/get_data.php");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
httpPost.setHeader("Pragma", "no-cache");
HttpResponse httpResponse = httpClient.execute(httpPost);
String result = EntityUtils.toString(httpResponse.getEntity());
if(result.equals("error")) {
return false;
}
result = result.replaceAll("\"", "\\\"");
JSONArray jsonArray = new JSONArray(result);
// code which receive and parse data from JSON
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
If you want to get some more information/pieces of code, write in comments.
Thanks for your help
You need to trace you requests by some monitoring program. After that you can see what node creates a delay. And pls show this data.
I am in a ditch since last few days trying out to get this,but not able to bring out any desired results.I will try to make myself clear that what i am looking for in following points:
I am working on android app,that will update the location of the user on the server using servlets(on my localhost).There is no problem regarding this,all is working fine.
The real problem that came in my way was when i was trying to get response from server back to android device,i just want to return a simple string,or something like that,Most likely a parameter,that will be utilized by the android app.Then i came to know about the json thing that i have to use it for doing what i am looking for.I have searched a lot about it,found some code too,but not able to use it well,
So my questions are
Is it possible to retrieve response from the servlet,and extract the required values from it without using json or any parsing technique,because i needed something like a single string only.
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet();
URI address=new URI("http://xxx.xxx.xxx.xxx:8080/MyServlet");
request.setUri(address);
HttpResponse response=client.execute(request);
The code from the android device requesting the response and the servlet are shown above,however when i call the toString method on response.toString() in android device,it yield me a string with some sequence of numbers,which are of no use to me.
HELP! HELP! HELP!
A simple example of it might help me up,
You could use a servlet that generates plain text result without any encoding technique.
On the server side, just replace your doGet function to look like that:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
On the client side, you could use the following code:
try {
final HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://SERVLET_URL/");
HttpResponse response = httpClient.execute(httpGet);
final HttpEntity entity = response.getEntity();
Log.i(TAG, "Servlet Result: " + EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException", e);
} catch (ParseException e) {
Log.e(TAG, "ParseException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
Hello all in my doe I have a try catch and I am catching the exception from a webservice
However If I run my web service in Firefox Poster add-on I get a response as well as a stastus exception
This obviously is not ALL the code but basically the exception is happening at getInputStream()
How can I get the response from the exception?
try{
//Get Response
stream = connection.getInputStream();
} catch (Exception e) {
throw new CustomException("Exception - " + e.getMessage());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int code = connection.getResponseCode();
String msg = connection.getResponseMessage();
These methods will still throw IOException if you can't reach the server. But if the server responds, even with an error, these methods give you access to the response.
I'm trying to retrieve a json string from a comet URL link.
Here is the API link: http://www.plurk.com/API#realtime
Here is the description:
You'll get an URL from /APP/Realtime/getUserChannel and you do GET requests to this URL to get new data. Your request will sleep for about 50 seconds before returning a response if there is no new data added to your channel. You won't get notifications on responses that the logged in user adds, but you will get notifications for new plurks.
I was able to obtain the comet_server url and paste that to firefox and get the result manually. However, when I tried to get these json string in android, I only got timeout error.
01:48:51.698 com.net.xerothermic.plurk INFO PLURK http://comet58.plurk.com:80/comet?channel=...&offset=0
01:53:43.680 com.net.xerothermic.plurk ERROR PLURK HTTP con. get
response error:Connection timed out
Here is the code I used to retrieve the data.
URL url = new URL(urlString);
HttpURLConnection conn = null;
try
{
conn = (HttpURLConnection) url.openConnection();
}
catch (IOException ex)
{
Log.e("PLURK", "HTTP con. open error:" + ex.getMessage());
return "";
}
try
{
conn.setRequestMethod("GET");
}
catch (ProtocolException ex)
{
Log.e("PLURK", "HTTP con. set method error:" + ex.getMessage());
}
try
{
return conn.getResponseMessage();
}
catch (IOException ex)
{
Log.e("PLURK", "HTTP con. get response error:" + ex.getMessage());
return "";
}
Any suggestion is much appreciated!
EDIT: here is the output from a browser. Did I miss to set some properties?
Even though the timeout value was set to 0 by default (meaning wait infinitely), I found I still need to explicit set the timeout value in order to not raise IOException.
setConnectTimeout(70000);
setReadTimeout(70000);
This is only needed on android but not Windows...