I'm searching for a best practice to handle errors in an HttpURLConnection especially if the host is not available. How did I have to change my source?:
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
you will get different responsecode using connection.getResponseCode()
Check for the response codes for host not available and you will be set.
Related
I'm getting a little bit confused about how properly close/manage an URLConnection/HttpURLConnection, the next code shows how I'm deal with it:
String someIP = "...";
URL url = new URL(someIP);
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
while ((res = br.readLine()) != null) {
cad.append(res);
}
}
I'm thinking to change the implementation to the next one, using an HttpURLConnection and closing later in finally clause:
String someIP = "...";
URL url = new URL(someIP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try (InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr)) {
while ((res = br.readLine()) != null) {
cad.append(res);
}
}
catch (Exception e) {
//ex....
}
finally {
if (conn != null) {
conn.disconnect();
}
}
It is enough to use a try with resources to properly close the BufferedReader, InputStreamReader and URLConnection? Or the second implementation is better, what advices could you give me to handle it.
I want to get data from an web service and after that to display it in a listView. So I made a function that get the data from the service, but when I tested it I discovered something unexpectedly. When I tested it as a call in the main function of the java class, it works, it returns me the data, but when I use it in the listView class, it doesn't. After some debugging, I still don't get why it doesn't work, but I observed that the only difference is that when the function is called in the main function, the URLConnection begins with sun.net.www.protocol.http.Http.URLConnection:http://... and when it's called in the listView class it begins with com.android.okhttp.internal.huc.HttpURLConnectionImpl:http//.. .
public static String getDataFromServer(String url) {
BufferedReader inputStream = null;
URL dataUrl = null;
String data = null;
//handle url exception
try {
dataUrl = new URL(url);
try {
URLConnection dc = dataUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
try {
inputStream = new BufferedReader(new InputStreamReader(dc.getInputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) { System.out.println(e.getMessage());}
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = inputStream.readLine())!=null)
sb.append(line + "\r\n");
data = sb.toString();
} catch (IOException e) { System.out.println(e.getMessage());
}
} catch (MalformedURLException e) { System.out.println(e.getMessage());}
return data;
}
do somthing like that :
String url = "http://youaddres.com/path";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//if it is post
con.setRequestMethod("POST");
String me = "{\"json\":\"" + json+ "\",\"json\":\"" + json+"\"}";
OutputStream os = con.getOutputStream();
os.write(me.getBytes());
os.flush();
InputStream inputStr = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStr));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String = response = sb.toString();
Following piece of code was working for the last three years, but all of a sudden it throws connection timed out only in server, but works as intended in localhost.
Any comments ?
public String getWikiContent(String query) {
StringBuilder builder = new StringBuilder();
String path = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=" + query + "&format=json&redirects";
try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Content-Type",
"application/json");
if (urlConn.getResponseCode() != 200) {
throw new IOException(urlConn.getResponseMessage());
}
InputStream is = urlConn.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = buff.readLine()) != null) {
builder.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return builder.toString();
}
For some reasons its a network issue, just adding a proxy server fixed it.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url,port));
URLConnection urlConn = url.openConnection(proxy);
String urlStr = "nana.com/nana/api/v1"
HttpURLConnection conn = null;
BufferedReader rd = null;
StringBuilder sb = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
else {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
}
} catch (IOException i) {
i.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
This is my connection and I don't really want to use apache. I want my application to display some error message if the server is unreachable but instead it crashes and I am sort of out of ideas.
Try this way
try {
String urlStr = "nana.com/nana/api/v1";
HttpURLConnection conn = null;
BufferedReader rd = null;
StringBuilder sb = null;
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Android Application");
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(10 * 1000);
conn.connect();
if (conn.getResponseCode() == 200) {
rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
}else{
throw new IOException(conn.getResponseMessage());
}
} catch (Throwable e) {
e.printStackTrace();
}
The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}