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();
Related
I am using the GitHub API to fetch files from a repository. I have the functionality implemented and it does work, I download the needed files but I found something strange, out of the 4 files I get, one is empty (no content inside) even though when I go the to repository and open it there it is clearly with content. The rest of the files have their content in when downloaded. Any idea why that happens?
Here is my code:
public int downloadFromGithub(String repo, String fileName) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", ****);
connection.setRequestProperty("Accept", ****);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && fileName!=null)
{
return saveFile(connection, fileName);
}
else { return connection.getResponseCode();}
}
public void downloadMultipleFilesFromGithub(String repo,String directoryPath) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", *****);
connection.setRequestProperty("Accept", "***");
String response = getResponseBody(connection);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray array = jsonObj.getJSONArray("tree");
for (int i=0; i < array.length(); i++) {
System.out.println(array.getJSONObject(i).get("path"));
String path = array.getJSONObject(i).get("path").toString();
if(path.contains("Scripts")){
String fileName = path.replace(scriptsDirectoryReplace, "");
downloadFromGithub(scriptsRepositoryDirectory+fileName,fileName);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String getResponseBody(HttpURLConnection conn) {
BufferedReader br = null;
StringBuilder body = null;
String line = "";
try {
br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
body = new StringBuilder();
while ((line = br.readLine()) != null)
body.append(line);
return body.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int saveFile(HttpURLConnection connection, String fileName) throws IOException {
// opens input stream from the HTTP connection
String saveFilePath = fileSaveDirectory + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream writer = new FileOutputStream(saveFilePath);
InputStream reader = connection.getInputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
reader.close();
writer.close();
return connection.getResponseCode();
}
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().
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
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.
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);
}
}