Search in sources :

Example 11 with Request

use of com.android.volley.Request in project BestPracticeApp by pop1234o.

the class MainActivity method requestOkHttpPost.

private void requestOkHttpPost() {
    final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    new Thread(new Runnable() {

        @Override
        public void run() {
            if (okHttpClient == null) {
                okHttpClient = new OkHttpClient();
            }
            okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
            RequestBody requestBody = RequestBody.create(JSON, "{\"key\":\"value\"}");
            okhttp3.Request request = builder.url("http://www.google.com").post(requestBody).build();
            okhttp3.Response response = null;
            try {
                response = okHttpClient.newCall(request).execute();
                // 注意这里是string()不是toString();
                String s = response.body().string();
                Log.i(TAG, "requestOkHttpPost: " + s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) StringRequest(com.android.volley.toolbox.StringRequest) Request(com.android.volley.Request) IOException(java.io.IOException) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 12 with Request

use of com.android.volley.Request in project android-volley by mcxiaoke.

the class BasicNetworkTest method headersAndPostParams.

@Test
public void headersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
        }

        @Override
        protected void deliverResponse(String response) {
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
        }
    };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}
Also used : StringEntity(org.apache.http.entity.StringEntity) MockHttpStack(com.android.volley.mock.MockHttpStack) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HashMap(java.util.HashMap) Request(com.android.volley.Request) NetworkResponse(com.android.volley.NetworkResponse) ProtocolVersion(org.apache.http.ProtocolVersion) Test(org.junit.Test)

Example 13 with Request

use of com.android.volley.Request in project saga-android by AnandChowdhary.

the class MusicDownloader method startDownload.

public static void startDownload(final Context context, final String songName, final String artistName, final DownloaderListener listener) {
    listener.showProgressBar();
    String url = "http://162.243.144.151/new_api.php?q=" + songName.replace(" ", "%20");
    if (artistName != null) {
        url += "&r=" + artistName.replace(" ", "%20");
    }
    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            if (response.length() != 0) {
                try {
                    final String[] fileName = new String[1];
                    final JSONObject jsonObject = new JSONObject(response);
                    String BASE_URL = "http://YouTubeInMP3.com/fetch/?video=http://www.youtube.com/watch?v=";
                    final DownloadManager dMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                    final String urlString = BASE_URL + jsonObject.getString("id");
                    final URL url = new URL(urlString);
                    new AsyncTask<Void, Void, String>() {

                        @Override
                        protected String doInBackground(Void... voids) {
                            try {
                                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                                urlConnection.setInstanceFollowRedirects(true);
                                return urlConnection.getContentType();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(String result) {
                            Log.d("Content type: ", result);
                            if ("audio/mpeg".equals(result)) {
                                listener.hideProgressBar();
                                Uri uri = Uri.parse(urlString);
                                DownloadManager.Request dr = new DownloadManager.Request(uri);
                                if (artistName == null) {
                                    try {
                                        fileName[0] = jsonObject.getString("title");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    fileName[0].replaceAll("(?i)\\b(official|lyrics|lyric|video|song)\\b", "");
                                    fileName[0].trim().replaceAll(" +", " ");
                                } else {
                                    fileName[0] = songName;
                                }
                                fileName[0] += ".mp3";
                                dr.setTitle(fileName[0]);
                                dr.setDestinationUri(Uri.fromFile(new File(Utils.getStoragePath(context) + "/" + fileName[0])));
                                dMgr.enqueue(dr);
                                Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show();
                                listener.onSuccess();
                                getSongInfo(context, fileName[0].substring(0, fileName[0].length() - 4), songName, artistName);
                            } else {
                                listener.hideProgressBar();
                                Toast.makeText(context, "Nothing found, sorry. Try again later", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                listener.hideProgressBar();
                Toast.makeText(context, "Nothing found, sorry. Try again later", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(context, context.getString(R.string.error_connect), Toast.LENGTH_SHORT).show();
            listener.hideProgressBar();
        }
    });
    request.setShouldCache(false);
    VolleySingleton.getInstance(context).getRequestQueue().add(request);
}
Also used : VolleyError(com.android.volley.VolleyError) StringRequest(com.android.volley.toolbox.StringRequest) AsyncTask(android.os.AsyncTask) Request(com.android.volley.Request) StringRequest(com.android.volley.toolbox.StringRequest) JSONException(org.json.JSONException) IOException(java.io.IOException) DownloadManager(android.app.DownloadManager) Uri(android.net.Uri) URL(java.net.URL) IOException(java.io.IOException) JSONException(org.json.JSONException) Response(com.android.volley.Response) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) File(java.io.File)

Example 14 with Request

use of com.android.volley.Request in project SimplifyReader by chentao0707.

the class OkHttpStack method performRequest.

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());
    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }
    setConnectionParametersForRequest(okHttpRequestBuilder, request);
    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();
    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));
    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }
    return response;
}
Also used : Call(com.squareup.okhttp.Call) OkHttpClient(com.squareup.okhttp.OkHttpClient) Headers(com.squareup.okhttp.Headers) Request(com.android.volley.Request) BasicStatusLine(org.apache.http.message.BasicStatusLine) Response(com.squareup.okhttp.Response) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

Request (com.android.volley.Request)14 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 Response (com.android.volley.Response)5 StringRequest (com.android.volley.toolbox.StringRequest)5 VolleyError (com.android.volley.VolleyError)4 StringEntity (org.apache.http.entity.StringEntity)4 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)4 NetworkResponse (com.android.volley.NetworkResponse)3 MockHttpStack (com.android.volley.mock.MockHttpStack)3 OkHttpClient (okhttp3.OkHttpClient)3 ProtocolVersion (org.apache.http.ProtocolVersion)3 DownloadManager (android.app.DownloadManager)2 Uri (android.net.Uri)2 Response (com.squareup.okhttp.Response)2 DeleteRequest (io.swagger.client.request.DeleteRequest)2 GetRequest (io.swagger.client.request.GetRequest)2 PatchRequest (io.swagger.client.request.PatchRequest)2 PostRequest (io.swagger.client.request.PostRequest)2 PutRequest (io.swagger.client.request.PutRequest)2