import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
+import android.support.annotation.NonNull;
import android.util.Log;
+import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
*
*
*/
- public static byte[] httpGetBytes(String url, int timeoutMs)
+ public static void httpGetBytes(String url, int timeoutMs, @NonNull IReceivedMessageCallback callback)
{
HttpURLConnection httpConn = null;
InputStream inputStream = null;
- byte[] receivedData = new byte[0];
-
int timeout = timeoutMs;
if (timeoutMs < 0)
{
if (inputStream == null)
{
Log.w(TAG, "httpGet: Response Code Error: " + responseCode + ": " + url);
- return (receivedData);
+ callback.onErrorOccurred(new NullPointerException());
+ callback.onCompleted();
+ return;
}
}
catch (Exception e)
{
httpConn.disconnect();
}
- return (receivedData);
+ callback.onErrorOccurred(e);
+ callback.onCompleted();
+ return;
}
// 応答を確認する
- BufferedReader reader = null;
- int count = 0;
try
{
+ int contentLength = httpConn.getContentLength();
byte[] buffer = new byte[BUFFER_SIZE];
- int c;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- reader = new BufferedReader(new InputStreamReader(inputStream));
- while ((c = reader.read()) != -1)
+ int readBytes = 0;
+ int readSize = inputStream.read(buffer, 0, BUFFER_SIZE);
+ while (readSize != -1)
{
- out.write(c);
- count++;
+ callback.onReceive(readBytes, contentLength, readSize, buffer);
+ readBytes += readSize;
+ readSize = inputStream.read(buffer, 0, BUFFER_SIZE);
}
- receivedData = out.toByteArray();
- Log.v(TAG, "RECEIVED " + count + " BYTES. ");
+ Log.v(TAG, "RECEIVED " + readBytes + " BYTES. (contentLength : " + contentLength + ")");
+ inputStream.close();
}
catch (Exception e)
{
Log.w(TAG, "httpGet: exception: " + e.getMessage());
e.printStackTrace();
+ callback.onErrorOccurred(e);
}
finally
{
try
{
- if (reader != null)
- {
- reader.close();
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- try
- {
inputStream.close();
}
catch (Exception e)
e.printStackTrace();
}
}
- return (receivedData);
+ callback.onCompleted();
}
+
/**
*
*
}
return (replyString);
}
+
+ public interface IReceivedMessageCallback
+ {
+ void onCompleted();
+ void onErrorOccurred(Exception e);
+ void onReceive(int readBytes, int length, int size, byte[] data);
+ }
}