How to read variable amount of json data from url? - android

I am using the following code to read json data from url , but it has fixed length of 500 for the json data. How can I ensure that all the data(variable length) is always read.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Thanks.
Reference

InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + newLine);
}
String result = sb.toString();

byte[] data = new byte[1024];
int bytesRead = inputstream.read(data);
while(bytesRead != -1) {
doSomethingWithData(data, bytesRead);
bytesRead = inputstream.read(data);
}

Related

How to get PDF file from HttpUrlConnection response in Android Java?

I am getting pdf file in response of API, I am using HttpUrlConnection (Android Java). I am unable to get pdf file from the response.
My code to get response is:
URL url = new URL(RESULT_DOWNLOAD_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(90000);
connection.setReadTimeout(90000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/pdf");
connection.setRequestProperty("Accept", "application/pdf");
connection.setRequestProperty("access-token", resultAccessToken);
connection.setChunkedStreamingMode(1024);
connection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("reference",reference);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
byte[] payload = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
int progressPercent = 0;
int offset = 0;
int bufferLength = payload.length / 100;
while(progressPercent < 100) {
os.write(payload, offset, bufferLength);
offset += bufferLength;
++progressPercent;
this.publishProgress(progressPercent);
}
os.write(payload, offset, payload.length % 100);
os.flush();
os.close();
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
resultResponse = inputStreamToString(inputStream);
Log.d(TAG, "Response : " + resultResponse);
}
private static String inputStreamToString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
return out.toString();
}
Response is like(for understanding, I converted it in string form):
I want to download file from this response, response is returning pdf file.
Add this code...
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
String FolderPath = "Images/"
File folder = null;
if(Build.VERSION.SDK_INT >= 29){ //Build.VERSION_CODES.R
folder = new File(context.getFilesDir() + "/" + FolderPath);
}else {
folder = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderPath);
}
if (!folder.exists())
folder.mkdirs();
String FilePath = folder.getAbsolutePath() + "/"
+ Path.substring(Path.lastIndexOf('/') + 1);
OutputStream output = new FileOutputStream(FilePath, false);
byte data[] = new byte[8192];
int count = -1;
while ((count = inputStream.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
inputStream.close();
}

ServerResponse 404 while uploading image to server

I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.
Here is my code
class SaveFile extends AsyncTask<String,String,String>
{
FileInputStream fileInputStream;
HttpURLConnection connection;
URL url;
DataOutputStream outputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedImagePath);
//selectedImagePath = path of Image in phonememory
#Override
protected String doInBackground(String... params)
{
Log.v(TAG,"Image path is " + selectedImagePath);
try
{
fileInputStream = new FileInputStream(selectedFile);
url = new URL(SEND_IMAGE);
connection= (HttpURLConnection)url.openConnection();
Log.v(TAG,"connection established");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
//connection.setRequestProperty("image1",selectedImagePath);
//connection.setRequestProperty("user_id","1");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--*****\r\n");
outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
outputStream.writeBytes("\r\n");
//outputStream.writeBytes("--*****\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer,0,bufferSize);
while (bytesRead>0)
{
outputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****--\r\n");
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Log.v(TAG,"Response is " +sb.toString());
}
Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
Log.v("UploadImage"," " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
but I am getting serverResponse 404
I tried solutions like Uploading Image to Server - Android but not worked.
I searched a lot.but couldnt find solution
Please Help!!
I want to say that this maybe a server error. 404 in most cases is an error that says, "you have used wrong url". Check whether this url is correct.try to upload your data in your browser.

Reading long string from socket in Android issue

I am getting long string data from server via socket and there is reading issue .
Data is around 10 MB .
private String createSocketConnection() throws IOException {
String result = "";
{
String host = ServiceUrlManager.socketIP;
int port = ServiceUrlManager.socketPort;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
socket.setSoTimeout(timeOut);
Log.d(TAG, ":::::Socket Connection " + socket.isConnected());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(createMSG());
dataOutputStream.write(sockecData);
dataOutputStream.flush();
//Read data from server connection
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
for(int s; (s=inputStream.read(buffer)) != -1; )
{
baos.write(buffer, 0, s);
}
String data = ISOUtil.hexString(baos.toByteArray());
result = data.substring(0, baos.toByteArray().length); // response message
Log.d(TAG, "::::Response " + result);
}
return result;
}
BufferedReader in =
new BufferedReader(
new InputStreamReader(inputStream.getInputStream()));
StringBuilder sb= new StringBuilder();
while(br.readLine!=null){
sb.append(br.readLine());
}

read text file returned by URL

This URL return & open text file directly, i just want to read its content how can i do it
http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=en&tl=gu&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=this+is+translate+demo
i have tried
public static String translate(String sl, String tl, String text) throws IOException{
// fetch
URL url = new URL("https://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=" +
sl + "&tl=" + tl + "&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=" +
URLEncoder.encode(text, "UTF-8"));
Log.d("URL", ":: "+url);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Something Else");
Log.d("URL", ":: After opening Connection");
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
Log.d("URL", ":: br "+br);
String result = br.readLine();
br.close();
// parse
Log.d("URL", ":: "+result);
result = result.substring(2, result.indexOf("]]") + 1);
StringBuilder sb = new StringBuilder();
String[] splits = result.split("(?<!\\\\)\"");
for(int i = 1; i < splits.length; i += 8)
sb.append(splits[i]);
return sb.toString().replace("\\n", "\n").replaceAll("\\\\(.)", "$1");
}
If Your Url directly open's the Text File then this code reads the TextFile and print's also as follows:
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

file not found exception

i am working in android. i want to integrate foursquare with my application.
for functioning of check in at a place. i am using this following code:-
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
}
but this is generating file not found exception. please help me what mistake i have done.
thank you in advance.
Try with following approach
read and write data from URL
void readAndWriteFromWeb(){
//make connection
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setAllowUserInteraction(true);
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("ConnectionTimeout", "12000");
httpURLConnection.setRequestProperty("Content-Length", "" + request.length);
//write data
OutputStream out = httpURLConnection.getOutputStream();
out.write(request);
out.flush();
//Log.e("Request URL "+url, "Request Data "+request);
//read data
InputStream inputStream = httpURLConnection.getInputStream();
int length = httpURLConnection.getContentLength();
//Log.e("Content Length", "" + length);
int readLength = 0;
int chunkSize = 1024;
int readBytes = 0;
byte[] data = new byte[chunkSize];
StringBuilder builder = new StringBuilder();
while((readBytes = inputStream.read(data)) != -1){
builder.append(new String(data,0,readBytes).trim());
readLength += readBytes;
//Release the memory.
data = null;
//Check the remaining length
if((length - readLength) < chunkSize){
if((length - readLength) == 0){
break;
}
data = new byte[((length) - readLength)];
}else{
data = new byte[chunkSize];
}
}
}

Categories

Resources