Search in sources :

Example 26 with Request

use of com.squareup.okhttp.Request in project sbt-android by scala-android.

the class DribbbleSearch method search.

@WorkerThread
public static List<Shot> search(String query, @SortOrder String sort, int page) {
    String html = null;
    // e.g https://dribbble.com/search?q=material+design&page=7&per_page=12
    HttpUrl url = new HttpUrl.Builder().scheme("https").host("dribbble.com").addPathSegment("search").addQueryParameter("q", query).addQueryParameter("s", sort).addQueryParameter("page", String.valueOf(page)).addQueryParameter("per_page", "12").build();
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    try {
        Response response = client.newCall(request).execute();
        html = response.body().string();
    } catch (IOException ioe) {
        return null;
    }
    if (html == null)
        return null;
    Elements shotElements = Jsoup.parse(html, HOST).select("li[id^=screenshot]");
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy");
    List<Shot> shots = new ArrayList<>(shotElements.size());
    for (Element element : shotElements) {
        Shot shot = parseShot(element, dateFormat);
        if (shot != null) {
            shots.add(shot);
        }
    }
    return shots;
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Element(org.jsoup.nodes.Element) Request(com.squareup.okhttp.Request) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Elements(org.jsoup.select.Elements) HttpUrl(com.squareup.okhttp.HttpUrl) Response(com.squareup.okhttp.Response) SimpleDateFormat(java.text.SimpleDateFormat) Shot(io.plaidapp.data.api.dribbble.model.Shot) WorkerThread(android.support.annotation.WorkerThread)

Example 27 with Request

use of com.squareup.okhttp.Request in project incubator-weex by apache.

the class HotRefreshManager method connect.

public boolean connect(String url) {
    OkHttpClient httpClient = new OkHttpClient();
    Request request = new Request.Builder().url(url).addHeader("sec-websocket-protocol", "echo-protocol").build();
    WebSocketCall.create(httpClient, request).enqueue(new WXWebSocketListener(url));
    return true;
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request)

Example 28 with Request

use of com.squareup.okhttp.Request 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);
        }
    });
}
Also used : Response(com.squareup.okhttp.Response) OkHttpClient(com.squareup.okhttp.OkHttpClient) Callback(com.squareup.okhttp.Callback) Request(com.squareup.okhttp.Request) IOException(java.io.IOException)

Example 29 with Request

use of com.squareup.okhttp.Request 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;
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) FileNotFoundException(java.io.FileNotFoundException) Intent(android.content.Intent) IOException(java.io.IOException) Uri(android.net.Uri) ResponseBody(com.squareup.okhttp.ResponseBody) Response(com.squareup.okhttp.Response) RandomAccessFile(java.io.RandomAccessFile) BufferedInputStream(java.io.BufferedInputStream) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 30 with Request

use of com.squareup.okhttp.Request 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;
}
Also used : Response(com.squareup.okhttp.Response) JsonElement(com.google.gson.JsonElement) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonParser(com.google.gson.JsonParser)

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