use of com.squareup.okhttp.Response in project pictureapp by EyeSeeTea.
the class SurveyChecker method getEvents.
/**
* Get events filtered by program orgUnit and between dates.
*/
public static List<EventExtended> getEvents(String program, String orgUnit, Date minDate, Date maxDate) throws ApiCallException {
Response response;
String DHIS_URL = PreferencesState.getInstance().getDhisURL();
String startDate = EventExtended.format(minDate, EventExtended.AMERICAN_DATE_FORMAT);
String endDate = EventExtended.format(new Date(maxDate.getTime() + (8 * 24 * 60 * 60 * 1000)), EventExtended.AMERICAN_DATE_FORMAT);
String url = SurveyCheckerStrategy.getApiEventUrl(DHIS_URL, program, orgUnit, startDate, endDate);
Log.d(TAG, url);
url = ServerApiUtils.encodeBlanks(url);
response = ServerApiCallExecution.executeCall(null, url, "GET");
JSONObject events = null;
try {
events = new JSONObject(ServerApiUtils.getReadableBodyResponse(response));
} catch (JSONException ex) {
throw new ApiCallException(ex);
}
JsonNode jsonNode = ServerApiUtils.getJsonNodeMappedResponse(events);
return getEvents(jsonNode);
}
use of com.squareup.okhttp.Response in project incubator-weex by apache.
the class Downloader method download.
public static void download(String url, final DownloadCallback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
callback.onError(e);
}
@Override
public void onResponse(Response response) throws IOException {
callback.handleResponse(response);
}
});
}
use of com.squareup.okhttp.Response in project remusic by aa112901.
the class DownloadTask method run.
@Override
public void run() {
Log.e("start", completedSize + "");
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_PREPARE;
// id = (saveDirPath + fileName).hashCode() + "";
onPrepare();
InputStream inputStream = null;
BufferedInputStream bis = null;
try {
dbEntity = downFileStore.getDownLoadedList(id);
file = new RandomAccessFile(saveDirPath + fileName, "rwd");
if (dbEntity != null) {
completedSize = dbEntity.getCompletedSize();
totalSize = dbEntity.getTotalSize();
}
if (file.length() < completedSize) {
completedSize = file.length();
}
long fileLength = file.length();
if (fileLength != 0 && totalSize == fileLength) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_COMPLETED;
totalSize = completedSize = fileLength;
dbEntity = new DownloadDBEntity(id, totalSize, completedSize, url, saveDirPath, fileName, artist, downloadStatus);
downFileStore.insert(dbEntity);
Log.e(TAG, "file is completed , file length = " + fileLength + " file totalsize = " + totalSize);
Toast.makeText(mContext, fileName + "已经下载完成", Toast.LENGTH_SHORT).show();
onCompleted();
return;
} else if (fileLength > totalSize) {
completedSize = 0;
totalSize = 0;
}
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_START;
onStart();
Request request = new Request.Builder().url(url).header("RANGE", // Http value set breakpoints RANGE
"bytes=" + completedSize + "-").addHeader("Referer", url).build();
Log.e("comlesize", completedSize + "");
file.seek(completedSize);
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
if (responseBody != null) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_DOWNLOADING;
if (totalSize <= 0)
totalSize = responseBody.contentLength();
inputStream = responseBody.byteStream();
bis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[4 * 1024];
int length = 0;
int buffOffset = 0;
if (dbEntity == null) {
dbEntity = new DownloadDBEntity(id, totalSize, 0L, url, saveDirPath, fileName, artist, downloadStatus);
downFileStore.insert(dbEntity);
}
while ((length = bis.read(buffer)) > 0 && downloadStatus != DownloadStatus.DOWNLOAD_STATUS_CANCEL && downloadStatus != DownloadStatus.DOWNLOAD_STATUS_PAUSE) {
file.write(buffer, 0, length);
completedSize += length;
buffOffset += length;
if (buffOffset >= UPDATE_SIZE) {
// Update download information database
if (totalSize <= 0 || dbEntity.getTotalSize() <= 0)
dbEntity.setToolSize(totalSize);
buffOffset = 0;
dbEntity.setCompletedSize(completedSize);
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
onDownloading();
}
}
// 这两句根据需要自行选择是否注释,注释掉的话由于少了数据库的读取,速度会快一点,但同时如果在下载过程程序崩溃的话,程序不会保存最新的下载进度
dbEntity.setCompletedSize(completedSize);
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
onDownloading();
}
} catch (FileNotFoundException e) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_ERROR;
onError(DownloadTaskListener.DOWNLOAD_ERROR_FILE_NOT_FOUND);
return;
// e.printStackTrace();
} catch (IOException e) {
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_ERROR;
onError(DownloadTaskListener.DOWNLOAD_ERROR_IO_ERROR);
return;
} finally {
// String nP = fileName.substring(0, path.length() - 5);
dbEntity.setCompletedSize(completedSize);
dbEntity.setFileName(fileName);
downFileStore.update(dbEntity);
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file != null)
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (totalSize == completedSize) {
String path = saveDirPath + fileName;
File file = new File(path);
Log.e("rename", path.substring(0, path.length() - 5));
boolean c = file.renameTo(new File(path + ".mp3"));
Log.e("rename", c + "");
downloadStatus = DownloadStatus.DOWNLOAD_STATUS_COMPLETED;
dbEntity.setDownloadStatus(downloadStatus);
downFileStore.update(dbEntity);
Uri contentUri = Uri.fromFile(new File(saveDirPath + fileName + ".mp3"));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
switch(downloadStatus) {
case DownloadStatus.DOWNLOAD_STATUS_COMPLETED:
onCompleted();
break;
case DownloadStatus.DOWNLOAD_STATUS_PAUSE:
onPause();
break;
case DownloadStatus.DOWNLOAD_STATUS_CANCEL:
downFileStore.deleteTask(dbEntity.getDownloadId());
File temp = new File(saveDirPath + fileName);
if (temp.exists())
temp.delete();
onCancel();
break;
}
}
use of com.squareup.okhttp.Response in project remusic by aa112901.
the class HttpUtil method getResposeJsonObject.
public static JsonObject getResposeJsonObject(String action1) {
try {
mOkHttpClient.setConnectTimeout(3000, TimeUnit.MINUTES);
mOkHttpClient.setReadTimeout(3000, TimeUnit.MINUTES);
Request request = new Request.Builder().url(action1).build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
String c = response.body().string();
// FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/" + System.currentTimeMillis() + ".txt");
// fileOutputStream.write(c.getBytes());
// fileOutputStream.close();
JsonParser parser = new JsonParser();
JsonElement el = parser.parse(c);
return el.getAsJsonObject();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use of com.squareup.okhttp.Response in project incubator-weex by apache.
the class DefaultWebSocketAdapter method connect.
@Override
public void connect(String url, @Nullable final String protocol, EventListener listener) {
this.eventListener = listener;
this.wsEventReporter = WSEventReporter.newInstance();
OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
if (protocol != null) {
builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
}
builder.url(url);
wsEventReporter.created(url);
Request wsRequest = builder.build();
WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, wsRequest);
try {
Field field = WebSocketCall.class.getDeclaredField("request");
field.setAccessible(true);
Request realRequest = (Request) field.get(webSocketCall);
Headers wsHeaders = realRequest.headers();
Map<String, String> headers = new HashMap<>();
for (String name : wsHeaders.names()) {
headers.put(name, wsHeaders.values(name).toString());
}
wsEventReporter.willSendHandshakeRequest(headers, null);
} catch (Exception e) {
e.printStackTrace();
}
webSocketCall.enqueue(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
ws = webSocket;
eventListener.onOpen();
Headers wsHeaders = response.headers();
Map<String, String> headers = new HashMap<>();
for (String name : wsHeaders.names()) {
headers.put(name, wsHeaders.values(name).toString());
}
wsEventReporter.handshakeResponseReceived(response.code(), Status.getStatusText(String.valueOf(response.code())), headers);
}
@Override
public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
if (type == WebSocket.PayloadType.BINARY) {
wsEventReporter.frameReceived(payload.readByteArray());
} else {
String message = payload.readUtf8();
eventListener.onMessage(message);
wsEventReporter.frameReceived(message);
}
payload.close();
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
eventListener.onClose(code, reason, true);
wsEventReporter.closed();
}
@Override
public void onFailure(IOException e) {
e.printStackTrace();
if (e instanceof EOFException) {
eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
wsEventReporter.closed();
} else {
eventListener.onError(e.getMessage());
wsEventReporter.frameError(e.getMessage());
}
}
});
}
Aggregations