com.android.volley.Request.Method Java Examples

The following examples show how to use com.android.volley.Request.Method. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HurlStack.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a response message contains a body.
 *
 * @param requestMethod request method
 * @param responseCode response status code
 * @return whether the response has a body
 * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
 */
/*
 * 检查请求结果 Response 是否存在 body
 *
 * 规则是这样的,要 必须 满足 5 点:
 * 1. 请求方法不是 HEAD 方法
 * 2. Status > 100
 * 3. Status < 200
 * 4. Status != 204
 * 5. Status != 304
 *
 */
private static boolean hasResponseBody(int requestMethod, int responseCode) {
    return requestMethod != Request.Method.HEAD &&
            !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK) &&
            responseCode != HttpStatus.SC_NO_CONTENT &&
            responseCode != HttpStatus.SC_NOT_MODIFIED;
}
 
Example #2
Source File: LoginFragment.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Call the login Api
 *
 * @param token    oath token we get from providers
 * @param provider facebook or google in our case
 */
private void loginWithProvider(final String token, final String provider) {

    final JSONObject requestObject = new JSONObject();

    try {
        requestObject.put(HttpConstants.PROVIDER, provider);
        requestObject.put(HttpConstants.ACCESS_TOKEN, token);
        requestObject.put(HttpConstants.DEVICE_ID, UserInfo.INSTANCE
                .getDeviceId());
        final BlRequest request = new BlRequest(Method.POST, HttpConstants.getApiBaseUrl()
                + ApiEndpoints.CREATE_USER, requestObject.toString(), mVolleyCallbacks);
        request.setRequestId(RequestId.CREATE_USER);
        addRequestToQueue(request, true, 0, true);
    } catch (final JSONException e) {
        // Should never happen
        Logger.e(TAG, e, "Error building create user json");
    }

}
 
Example #3
Source File: Act_NetworkListView.java    From android_volley_examples with Apache License 2.0 6 votes vote down vote up
private void loadPage() {
    RequestQueue queue = MyVolley.getRequestQueue();

    int startIndex = 1 + mEntries.size();
    JsonObjectRequest myReq = new JsonObjectRequest(Method.GET,
                                            "https://picasaweb.google.com/data/feed/api/all?q=kitten&max-results="
                                                    +
                                                    RESULTS_PAGE_SIZE
                                                    +
                                                    "&thumbsize=160&alt=json"
                                                    + "&start-index="
                                                    + startIndex,
                                                    null,
                                            createMyReqSuccessListener(),
                                            createMyReqErrorListener());

    queue.add(myReq);
}
 
Example #4
Source File: HttpClientStack.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 */
protected static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException {
    switch (request.getMethod()) {
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}
 
Example #5
Source File: HurlStack.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
private static void setConnectionParametersForRequest(
                HttpURLConnection connection, Request<?> request,
                HashMap<String, String> additionalHeaders, String userAgent)
                throws IOException, AuthFailureError {

    addHeadersToConnection(connection, userAgent, additionalHeaders);
    switch (request.getMethod()) {
        case Method.GET:
            // Not necessary to set the request method because connection
            // defaults to GET but
            // being explicit here.
            connection.setRequestMethod("GET");
            break;
        case Method.DELETE:
            connection.setRequestMethod("DELETE");
            break;
        case Method.POST:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case Method.PUT:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example #6
Source File: HttpClientStackTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void createPutRequest() throws Exception {
    TestRequest.Put request = new TestRequest.Put();
    assertEquals(request.getMethod(), Method.PUT);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPut);
}
 
Example #7
Source File: HttpClientStackTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void createPostRequestWithBody() throws Exception {
    TestRequest.PostWithBody request = new TestRequest.PostWithBody();
    assertEquals(request.getMethod(), Method.POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example #8
Source File: HttpClientStackTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void createHeadRequest() throws Exception {
    TestRequest.Head request = new TestRequest.Head();
    assertEquals(request.getMethod(), Method.HEAD);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpHead);
}
 
Example #9
Source File: HttpClientStackTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void createOptionsRequest() throws Exception {
    TestRequest.Options request = new TestRequest.Options();
    assertEquals(request.getMethod(), Method.OPTIONS);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpOptions);
}
 
Example #10
Source File: HurlStackTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForDeleteRequest() throws Exception {
    TestRequest.Delete request = new TestRequest.Delete();
    assertEquals(request.getMethod(), Method.DELETE);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("DELETE", mMockConnection.getRequestMethod());
    assertFalse(mMockConnection.getDoOutput());
}
 
Example #11
Source File: HurlStackTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForOptionsRequest() throws Exception {
    TestRequest.Options request = new TestRequest.Options();
    assertEquals(request.getMethod(), Method.OPTIONS);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("OPTIONS", mMockConnection.getRequestMethod());
    assertFalse(mMockConnection.getDoOutput());
}
 
Example #12
Source File: HttpClientStackTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void createDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example #13
Source File: GosScheduleSiteTool.java    From Gizwits-SmartBuld_Android with MIT License 5 votes vote down vote up
public void deleteTimeOnSite(String id, final OnResponListener reponse) {
	String httpurl = "http://api.gizwits.com/app/scheduler/" + id;
	StringRequest stringRequest = new StringRequest(Method.DELETE, httpurl, new Response.Listener<String>() {
		@Override
		public void onResponse(String arg0) {
			reponse.OnRespon(0, "OK");
		}
	}, new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			if (error.networkResponse != null) {
				if (error.networkResponse.statusCode == 404) {// 404:云端无法找到该条目,表示该条目已被删除
					reponse.OnRespon(0, "OK");
				}
			}
			reponse.OnRespon(1, error.toString());
			error.printStackTrace();
			Log.i("onSite", "删除失败" + error.toString());

		}
	}) {

		@Override
		public Map<String, String> getHeaders() throws AuthFailureError {
			return getHeaderWithToken();
		}

	};
	stringRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 3, 0));
	mRequestQueue.add(stringRequest);

}
 
Example #14
Source File: HttpClientStackTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void createGetRequest() throws Exception {
    TestRequest.Get request = new TestRequest.Get();
    assertEquals(request.getMethod(), Method.GET);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpGet);
}
 
Example #15
Source File: HttpClientStackTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testCreateDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example #16
Source File: HurlStackTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForPostWithBodyRequest() throws Exception {
    TestRequest.PostWithBody request = new TestRequest.PostWithBody();
    assertEquals(request.getMethod(), Method.POST);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("POST", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #17
Source File: HurlStackTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("POST", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #18
Source File: HurlStackTest.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForGetRequest() throws Exception {
    TestRequest.Get request = new TestRequest.Get();
    assertEquals(request.getMethod(), Method.GET);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("GET", mMockConnection.getRequestMethod());
    assertFalse(mMockConnection.getDoOutput());
}
 
Example #19
Source File: HurlStackTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testConnectionForDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("POST", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #20
Source File: HttpClientStackTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void createGetRequest() throws Exception {
    TestRequest.Get request = new TestRequest.Get();
    assertEquals(request.getMethod(), Method.GET);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpGet);
}
 
Example #21
Source File: HurlStackTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testConnectionForPatchWithBodyRequest() throws Exception {
    TestRequest.PatchWithBody request = new TestRequest.PatchWithBody();
    assertEquals(request.getMethod(), Method.PATCH);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("PATCH", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #22
Source File: HttpClientStackTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testCreatePutRequest() throws Exception {
    TestRequest.Put request = new TestRequest.Put();
    assertEquals(request.getMethod(), Method.PUT);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPut);
}
 
Example #23
Source File: Act_SsSslHttpClient.java    From android_volley_examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act__ss_ssl_http_client);

    mTvResult = (TextView) findViewById(R.id.tv_result);

    Button btnSimpleRequest = (Button) findViewById(R.id.btn_simple_request);
    btnSimpleRequest.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            
            // Replace R.raw.test with your keystore 
            InputStream keyStore = getResources().openRawResource(R.raw.test);
            
            
            // Usually getting the request queue shall be in singleton like in {@see Act_SimpleRequest}
            // Current approach is used just for brevity
            RequestQueue queue = Volley
                    .newRequestQueue(Act_SsSslHttpClient.this,
                                     new ExtHttpClientStack(new SslHttpClient(keyStore, "test123", 44401)));

            StringRequest myReq = new StringRequest(Method.GET,
                                                    "https://ave.bolyartech.com:44401/https_test.html",
                                                    createMyReqSuccessListener(),
                                                    createMyReqErrorListener());

            queue.add(myReq);
        }
    });
}
 
Example #24
Source File: HttpClientStackTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testCreatePostRequest() throws Exception {
    TestRequest.Post request = new TestRequest.Post();
    assertEquals(request.getMethod(), Method.POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example #25
Source File: HurlStackTest.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForPostWithBodyRequest() throws Exception {
    TestRequest.PostWithBody request = new TestRequest.PostWithBody();
    assertEquals(request.getMethod(), Method.POST);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("POST", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #26
Source File: AbstractBarterLiFragment.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the user info with just the first name and last name
 *
 * @param firstName The user's first name
 * @param lastName  The user's last name
 */
public void updateUserInfo(final String firstName, final String lastName) {

    final String url = HttpConstants.getApiBaseUrl()
            + ApiEndpoints.UPDATE_USER_INFO;

    final JSONObject mUserProfileObject = new JSONObject();
    final JSONObject mUserProfileMasterObject = new JSONObject();
    try {
        mUserProfileObject.put(HttpConstants.FIRST_NAME, firstName);
        mUserProfileObject.put(HttpConstants.LAST_NAME, lastName);
        mUserProfileMasterObject
                .put(HttpConstants.USER, mUserProfileObject);

        final BlMultiPartRequest updateUserProfileRequest = new BlMultiPartRequest(Method.PUT,
                                                                                   url, null,
                                                                                   mVolleyCallbacks);

        updateUserProfileRequest
                .addMultipartParam(HttpConstants.USER, "application/json",
                                   mUserProfileMasterObject
                                           .toString()
                );

        updateUserProfileRequest.setRequestId(RequestId.SAVE_USER_PROFILE);
        addRequestToQueue(updateUserProfileRequest, true, 0, true);

    } catch (final JSONException e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: HurlStackTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForHeadRequest() throws Exception {
    TestRequest.Head request = new TestRequest.Head();
    assertEquals(request.getMethod(), Method.HEAD);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("HEAD", mMockConnection.getRequestMethod());
    assertFalse(mMockConnection.getDoOutput());
}
 
Example #28
Source File: HurlStackTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForPatchWithBodyRequest() throws Exception {
    TestRequest.PatchWithBody request = new TestRequest.PatchWithBody();
    assertEquals(request.getMethod(), Method.PATCH);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("PATCH", mMockConnection.getRequestMethod());
    assertTrue(mMockConnection.getDoOutput());
}
 
Example #29
Source File: ProgrammaticAutocompleteToolbarActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a Geocoding API request and displays the result in a dialog.
 *
 * @see https://developers.google.com/maps/documentation/geocoding/intro
 */
private void geocodePlaceAndDisplay(AutocompletePrediction placePrediction) {
    // Construct the request URL
    final String apiKey = getString(R.string.places_api_key);
    final String url = "https://maps.googleapis.com/maps/api/geocode/json?place_id=%s&key=%s";
    final String requestURL = String.format(url, placePrediction.getPlaceId(), apiKey);

    // Use the HTTP request URL for Geocoding API to get geographic coordinates for the place
    JsonObjectRequest request = new JsonObjectRequest(Method.GET, requestURL, null,
        response -> {
            try {
                // Inspect the value of "results" and make sure it's not empty
                JSONArray results = response.getJSONArray("results");
                if (results.length() == 0) {
                    Log.w(TAG, "No results from geocoding request.");
                    return;
                }

                // Use Gson to convert the response JSON object to a POJO
                GeocodingResult result = gson.fromJson(
                    results.getString(0), GeocodingResult.class);
                displayDialog(placePrediction, result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> Log.e(TAG, "Request failed"));

    // Add the request to the Request queue.
    queue.add(request);
}
 
Example #30
Source File: HurlStackTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void connectionForPatchRequest() throws Exception {
    TestRequest.Patch request = new TestRequest.Patch();
    assertEquals(request.getMethod(), Method.PATCH);

    HurlStack.setConnectionParametersForRequest(mMockConnection, request);
    assertEquals("PATCH", mMockConnection.getRequestMethod());
    assertFalse(mMockConnection.getDoOutput());
}