Not able to convert String to InputStream for parsing XML - java

I am trying to parse XML code from a server to use in Android. The URL is working, and up to SB I get the XML. When converting String to InputStream i get this in the logcat : java.io.ByteArrayInputStream#9e7122d
any help ?
thanks !
private InputStream downloadUrl(String urlString) throws IOException {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(60000);
con.setReadTimeout(60000);
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
InputStream stream = IOUtils.toInputStream(sb, "UTF-8");
Log.d(TAG, "SB " + sb);
Log.d(TAG, "STREAM" + stream);
return stream;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}

There is no problem here to solve. The ByteArrayInputStream#9e7122d thing is just what ByteArrayInputStream.toString() returns.
BUT Why are you doing this? Loading the entire URL into memory adds latency and wastes space, and won't fit beyond a certain size. There is no benefit. Just return con.getInputStream().

Related

How to get response from a http connection in android

I'm trying to handle this API http://worldtimeapi.org
Here is my code :
#Nullable
public String getResponseFromHttpUrl(#NonNull URL gotUrl) {
Log.v(LOG_TAG, "URI : " + gotUrl);
String timeJSONString = null;
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
try {
urlConnection = (HttpURLConnection) gotUrl.openConnection();
InputStream inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
if (stringBuilder.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
timeJSONString = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.d(LOG_TAG, "Response : " + timeJSONString);
return timeJSONString;
}
But the problem is my method returns null.
As you can see in below:
V/NetworkUtils: URI : http://worldtimeapi.org/api/timezone/America/Denver
W/System.err: at com.example.timeonearth.NetworkUtils.getResponseFromHttpUrl(NetworkUtils.java:56)
D/NetworkUtils: Response : null
You need to Try getting the input stream from this you can then get the text data as so:-->
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://worldtimeapi.org/api/timezone/America/Denver");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other Inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.

Trouble with retriving data from a web service

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();

How to pass and read string from android to sql using JSON

Previously, i can access the string from php remotely. I find it difficult at first but AsyncTask did the work for me. Now, i can access the result of the query from php to sql server. But I would like to pass a string from my java class to php and as I googled some information, i saw some JSON post and get codes but i can't clearly understand them. Here's my code:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
The string is contained in "sb.toString()". Now how would I add a JSON something in my code to send string from java to php, and also get the result string from php to java as well. Thanks in advance for any help.
If you receive response as JSON format from server, make the json string to JSONObject first. And then read the json data for your use.
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
Your code already contains the answer of your question. After make url connection, just add parameter for sending your data to server with OutputStreamWriter as like you did for receive the response with InpustStreamReader.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here

Reading HttpURLConnection

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.
I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.
Thanks in advance!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
There are a bunch of things wrong with the code I posted in the question. Here is a working example:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It appears you are not connecting your HTTPUrlClient try con.connect()

HttpURLConnection helped me avoid NullPointerException

I encountered this really strange thing while using the HttpURLConnection today. I have the below code that basically reads data from a URL, and stores the data (after parsing it to a java object using GSON) into a Java object. The data is also simultaneously stored in another object that I have serialized and saved to a file. In the event my URL is not accessible, I read the data from the file. The URL is a secure URL that I can only access over the VPN. So to test my program, I disconnected from the VPN to see if I am able to read data from the file. The first code below throws me a null pointer, while the second one doesn't. The only difference as you can see is I am using HttpURLConnection in the second example. How does using it help? Anyone encountered something similar, or am I overlooking something? ;)
Code that throws nullpointer when URL can't be accessed -
public static void getInfoFromURL() throws IOException {
Gson gson = null;
URL url = null;
BufferedReader bufferedReader = null;
String inputLine = "";
try {
gson = new Gson();
url = new URL(addressURL);
bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
addressData = ((AddressData) gson.fromJson(inputLine,AddressData.class));
}
} catch (MalformedURLException mue) {
logger.error("Malformed URL exception " + mue+ " occured while accessing the URL ");
} catch (IOException ioe) {
logger.error("IO exception " + ioe+ " occured while accessing the URL ");
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Code that works fine:
public static void getInfoFromURL() throws IOException {
Gson gson = null;
URL url = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection =null;
String inputLine = "";
try {
gson = new Gson();
url = new URL(addressURL);
connection = (HttpURLConnection) url.openConnection(); //This seems to be helping
connection.connect();
bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
addressData = ((AddressData) gson.fromJson(inputLine,AddressData.class));
}
} catch (MalformedURLException mue) {
logger.error("Malformed URL exception " + mue+ " occured while accessing the URL ");
} catch (IOException ioe) {
logger.error("IO exception " + ioe+ " occured while accessing the URL ");
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}

Categories