Search in sources :

Example 11 with Request

use of com.squareup.okhttp.Request in project AisenWeiBo by wangdan.

the class WebDownloader method downloadBitmap.

@Override
public byte[] downloadBitmap(Context context, String url, ImageConfig config) throws Exception {
    Logger.v(url);
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DownloadProcess progress = config.getProgress();
        if (progress != null)
            progress.sendPrepareDownload(url);
        Request request = new Request.Builder().url(url).build();
        // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:27.0) Gecko/20100101 Firefox/27.0");
        Response response = GlobalContext.getOkHttpClient().newCall(request).execute();
        if (!(response.code() == HttpURLConnection.HTTP_OK || response.code() == HttpURLConnection.HTTP_PARTIAL)) {
            throw new TaskException(String.valueOf(TaskException.TaskError.failIOError));
        } else {
            // 图片大小
            int length = 0;
            try {
                String header = response.header("Content-Length");
                length = Integer.parseInt(header);
            } catch (Exception e) {
            }
            if (progress != null) {
                progress.sendLength(length);
            }
            InputStream in = response.body().byteStream();
            // 获取图片数据
            byte[] buffer = new byte[1024 * 8];
            int readLen = -1;
            int readBytes = 0;
            while ((readLen = in.read(buffer)) != -1) {
                readBytes += readLen;
                if (progress != null)
                    progress.sendProgress(readBytes);
                out.write(buffer, 0, readLen);
            }
            byte[] bs = out.toByteArray();
            // 如果图片没有下载完成,默认图片加载失败
            if (length != 0 && bs.length != length)
                return null;
            in.close();
            out.close();
            return bs;
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (config.getProgress() != null)
            config.getProgress().sendException(e);
        throw new Exception(e.getCause());
    }
}
Also used : Response(com.squareup.okhttp.Response) TaskException(org.aisen.android.network.task.TaskException) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TaskException(org.aisen.android.network.task.TaskException)

Example 12 with Request

use of com.squareup.okhttp.Request in project AisenWeiBo by wangdan.

the class WallpaperDownloadTask method doDownload.

// 下载壁纸
private File doDownload(File file) throws TaskException {
    if (!isRunning())
        throw new TaskException("-100", "");
    // 判断网络是否连接
    if (SystemUtils.getNetworkType(GlobalContext.getInstance()) == SystemUtils.NetWorkType.none) {
        throw new TaskException("", mContext.getResources().getString(org.aisen.android.R.string.comm_error_none_network));
    }
    // 先下载一个临时文件
    File tempFile = new File(file.getAbsolutePath() + ".tmp");
    // 如果图片没有content-length
    final int defaultLength = 8 * 1024 * 1024;
    // 开始下载图片
    try {
        total = 0;
        progress = 0;
        // 发布进度
        publishProgress(progress, total);
        Logger.d(TAG, "开始下载壁纸 ---> %s", mImageUrl);
        Request request = new Request.Builder().get().url(mImageUrl).build();
        mCall = httpClient.newCall(request);
        Response response = mCall.execute();
        if (response == null) {
            throw new TaskException(TaskException.TaskError.failIOError.toString());
        }
        int statusCode = response.code();
        if (!(statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_PARTIAL)) {
            throw new TaskException(TaskException.TaskError.failIOError.toString());
        }
        InputStream imageStream = null;
        // 写临时文件
        FileOutputStream out = new FileOutputStream(tempFile);
        try {
            String encoding = response.header("Content-Encoding");
            if (encoding != null && !TextUtils.isEmpty(encoding) && "gzip".equals(encoding)) {
                imageStream = new GZIPInputStream(response.body().byteStream());
                Logger.w(TAG, "解压gzip文件, 解压前大小:");
            } else {
                imageStream = response.body().byteStream();
            }
            try {
                total = response.body().contentLength();
            } catch (Exception e) {
                // 容错处理,如果未读到大小,默认为8M
                total = defaultLength;
            }
            Logger.d(TAG, "Content-Length = " + total);
            if (total < 0)
                total = defaultLength;
            // 获取图片数据
            byte[] buffer = new byte[1024 * 8];
            int readLen = -1;
            long lastPublishTime = 0l;
            while ((readLen = imageStream.read(buffer)) != -1) {
                if (!isRunning())
                    throw new TaskException("-100", "");
                progress += readLen;
                out.write(buffer, 0, readLen);
                Logger.v(TAG, "下载进度, %s / %s", getUnit(progress), getUnit(total));
                // 发布进度
                long now = System.currentTimeMillis();
                if (now - lastPublishTime > PUBLISH_INTERVAL_TIME) {
                    lastPublishTime = now;
                    publishProgress(progress, total);
                }
            }
            publishProgress(progress, progress);
            Logger.d(TAG, "total : " + total + "   readLen : " + readLen);
            out.flush();
        } catch (IOException e) {
            Logger.printExc(WallpaperDownloadTask.class, e);
            throw e;
        } finally {
            out.close();
            if (imageStream != null)
                imageStream.close();
        }
    // // 验证一下是否GZip压缩
    // try {
    // String encoding = response.header("Content-Encoding");
    // if (encoding != null && !TextUtils.isEmpty(encoding) &&
    // "gzip".equals(encoding)) {
    // File ttf = tempFile;
    // tempFile = decodeGZipFile(tempFile);
    // ttf.delete();
    // Logger.w(TAG, "解压gzip文件, 解压前大小:" + total + ", 解压后:" + tempFile.length());
    // }
    // } catch (Throwable e) {
    // Logger.printExc(WallpaperDownloadTask.class, e);
    // }
    } catch (Throwable e) {
        Logger.printExc(WallpaperDownloadTask.class, e);
        throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
    }
    Logger.d(TAG, "File-Length = " + tempFile.length());
    Logger.d(TAG, "下载文件成功,path = " + tempFile.getAbsolutePath());
    // 重命名之前,对临时文件,做一次图片校验,用BitmapFactory解析一下
    Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(tempFile.getAbsolutePath(), opts);
    // 如果解析的宽高度小于1,默认为非图片
    Logger.d(TAG, "图片解析尺寸 %s x %s", opts.outWidth, opts.outHeight);
    if (opts.outWidth < 1 && opts.outHeight < 1) {
        throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
    }
    Logger.d(TAG, "下载壁纸完成");
    if (!tempFile.renameTo(file))
        throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
    return file;
}
Also used : Options(android.graphics.BitmapFactory.Options) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) TaskException(org.aisen.android.network.task.TaskException) IOException(java.io.IOException) Response(com.squareup.okhttp.Response) GZIPInputStream(java.util.zip.GZIPInputStream) TaskException(org.aisen.android.network.task.TaskException) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 13 with Request

use of com.squareup.okhttp.Request in project openzaly by akaxincom.

the class ZalyHttpClient method get.

public byte[] get(String url) throws Exception {
    Request request = new Request.Builder().url(url).build();
    Response response = httpClient.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().bytes();
    } else {
        logger.error("http get url={} error.{}", url, response.message());
    }
    return null;
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request)

Example 14 with Request

use of com.squareup.okhttp.Request in project openzaly by akaxincom.

the class ZalyHttpClient method run.

public byte[] run(String url) throws Exception {
    Request request = new Request.Builder().url(url).build();
    Response response = httpClient.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().bytes();
    } else {
        logger.error("http post error.{}", response.message());
    }
    return null;
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request)

Example 15 with Request

use of com.squareup.okhttp.Request in project openzaly by akaxincom.

the class HttpTestPost method post.

static String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = client.newCall(request).execute();
    System.out.println("response = " + response.isSuccessful());
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) RequestBody(com.squareup.okhttp.RequestBody)

Aggregations

Request (com.squareup.okhttp.Request)111 Response (com.squareup.okhttp.Response)75 IOException (java.io.IOException)60 OkHttpClient (com.squareup.okhttp.OkHttpClient)37 RequestBody (com.squareup.okhttp.RequestBody)30 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 File (java.io.File)11 Callback (com.squareup.okhttp.Callback)10 InputStream (java.io.InputStream)7 Buffer (okio.Buffer)6 HttpUrl (com.squareup.okhttp.HttpUrl)5 MediaType (com.squareup.okhttp.MediaType)5 SocketTimeoutException (java.net.SocketTimeoutException)5 HashMap (java.util.HashMap)5 Call (com.squareup.okhttp.Call)4 ResponseBody (com.squareup.okhttp.ResponseBody)4 FileOutputStream (java.io.FileOutputStream)4 Activity (android.app.Activity)3 Intent (android.content.Intent)3