Java Code Examples for com.android.volley.Request.Method#GET

The following examples show how to use com.android.volley.Request.Method#GET . 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: 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 2
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 3
Source File: AddOrEditBookFragment.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
@Override
public void performNetworkQuery(
        final NetworkedAutoCompleteTextView textView,
        final String query) {

    if (textView.getId() == R.id.edit_text_title) {
        Logger.v(TAG, "Perform network query %s", query);

        final BlRequest request = new BlRequest(Method.GET, HttpConstants.getGoogleBooksUrl()
                + ApiEndpoints.VOLUMES, null, mVolleyCallbacks);
        request.setRequestId(RequestId.BOOK_SUGGESTIONS);

        final Map<String, String> params = new HashMap<String, String>(1);
        params.put(HttpConstants.Q, GoogleBookSearchKey.INTITLE + query);

        final Map<String, String> headers = new HashMap<String, String>(1);
        headers.put(HttpConstants.KEY, mGoogleBooksApiKey);

        request.setParams(params);
        request.setHeaders(headers);

        addRequestToQueue(request, false, 0, false);
    }
}
 
Example 4
Source File: TeamFragment.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(final LayoutInflater inflater,
                final ViewGroup container, final Bundle savedInstanceState) {
    init(container, savedInstanceState);
    mLoadedIndividually = false;
    final View view = inflater
            .inflate(R.layout.fragment_team, null);
    mGridView = (GridView) view.findViewById(R.id.team_grid);

    
    // Make a call to server
    try {

        final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl()
                        + ApiEndpoints.TEAM, null, mVolleyCallbacks);
        request.setRequestId(RequestId.TEAM);
        addRequestToQueue(request, true, 0,true);
    } catch (final Exception e) {
        // Should never happen
        Logger.e(TAG, e, "Error building report bug json");
    }
    return view;
}
 
Example 5
Source File: SelectPreferredLocationFragment.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch all the hangouts centered at the current location with the given radius without
 * category filter. This is used when there are no places with the categories supplied .
 *
 * @param location The location to search for hangouts
 * @param radius   Tghe search radius(in meters)
 */
private void fetchVenuesForLocationWithoutCategoryFilter(
        final Location location, final int radius) {

    final BlRequest request = new BlRequest(Method.GET, HttpConstants.getFoursquareUrl()
            + ApiEndpoints.FOURSQUARE_VENUES, null, mVolleyCallbacks);
    request.setRequestId(RequestId.FOURSQUARE_VENUES_WITHOUT_CATEGORIES);

    final Map<String, String> params = new HashMap<String, String>(7);

    params.put(HttpConstants.LL, String.format(Locale.US, "%f,%f", location
            .getLatitude(), location.getLongitude()));

    params.put(HttpConstants.RADIUS, String.valueOf(radius));

    params.put(HttpConstants.INTENT, HttpConstants.BROWSE);
    params.put(HttpConstants.CLIENT_ID, mFoursquareClientId);
    params.put(HttpConstants.CLIENT_SECRET, mFoursquareClientSecret);
    params.put(HttpConstants.V, FOURSQUARE_API_VERSION);

    request.setParams(params);
    addRequestToQueue(request, true, 0, false);
}
 
Example 6
Source File: ProfileFragment.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the book owner user details
 */

private void fetchUserDetailsFromServer(final String userid) {

    final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl()
            + ApiEndpoints.USERPROFILE, null, mVolleyCallbacks);
    request.setRequestId(RequestId.GET_USER_PROFILE);

    final Map<String, String> params = new HashMap<String, String>(2);

    params.put(HttpConstants.ID, String.valueOf(userid).trim());
    request.setParams(params);

    if (mIsLoggedInUser
            && SharedPreferenceHelper
            .getBoolean(R.string.pref_force_user_refetch)) {
        request.setShouldCache(false);
    }
    addRequestToQueue(request, true, 0, true);

}
 
Example 7
Source File: BaseGsonLoader.java    From android_tv_metro with Apache License 2.0 5 votes vote down vote up
public GsonRequest(String url, Type type, Map<String, String> headers,
                   Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.type = type;
    this.headers = headers;
    this.listener = listener;
}
 
Example 8
Source File: LoginFragment.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Call the password_reset Api
 *
 * @param email The entered email
 */

private void callForgotPassword(String email) {
    final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl()
            + ApiEndpoints.PASSWORD_RESET, null, mVolleyCallbacks);
    request.setRequestId(RequestId.REQUEST_RESET_TOKEN);
    mEmailForPasswordChange = email;
    final Map<String, String> params = new HashMap<String, String>(1);
    params.put(HttpConstants.EMAIL, email);
    request.setParams(params);
    addRequestToQueue(request, true, 0, true);
}
 
Example 9
Source File: HurlStack.java    From FeedListViewDemo with MIT License 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            addBodyIfExists(connection, request);
            connection.setRequestMethod("PATCH");
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 10
Source File: AddOrEditBookFragment.java    From barterli_android with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches the book info from server based on the ISBN number or book title
 *
 * @param isbn The ISBN Number of the book to get info for
 */
private void getBookInfoFromServer(final String isbn) {

    final BlRequest request = new BlRequest(Method.GET, HttpConstants.getGoogleBooksUrl()
            + ApiEndpoints.VOLUMES, null, mVolleyCallbacks);
    request.setRequestId(RequestId.GET_BOOK_INFO);

    final Map<String, String> params = new HashMap<String, String>(1);
    params.put(HttpConstants.Q, GoogleBookSearchKey.ISBN + isbn);

    final Map<String, String> headers = new HashMap<String, String>(1);
    headers.put(HttpConstants.KEY, mGoogleBooksApiKey);

    request.setParams(params);
    request.setHeaders(headers);

    addRequestToQueue(request, true, R.string.unable_to_fetch_book_info, false);

}
 
Example 11
Source File: HurlStack.java    From okulus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 12
Source File: SelectPreferredLocationFragment.java    From barterli_android with Apache License 2.0 4 votes vote down vote up
/**
 * Fetch all the hangouts centered at the current location with the given radius
 *
 * @param location The location to search for hangouts
 * @param radius   Tghe search radius(in meters)
 */
private void fetchVenuesForLocation(final Location location,
                                    final int radius) {

    if (location.getLatitude() == 0.0) {
        showEnableLocationDialog();
    } else {
        final BlRequest request = new BlRequest(Method.GET, HttpConstants.getFoursquareUrl()
                + ApiEndpoints.FOURSQUARE_VENUES, null, mVolleyCallbacks);
        request.setRequestId(RequestId.FOURSQUARE_VENUES);

        final Map<String, String> params = new HashMap<String, String>(7);

        params.put(HttpConstants.LL, String.format(Locale.US, "%f,%f", location
                .getLatitude(), location.getLongitude()));

        params.put(HttpConstants.RADIUS, String.valueOf(radius));

        final String foursquareCategoryFilter = FoursquareCategoryBuilder
                .init()
                .with(FoursquareCategoryBuilder.ARTS_AND_ENTERTAINMENT)
                .with(FoursquareCategoryBuilder.COLLEGE_AND_UNIVERSITY)
                .with(FoursquareCategoryBuilder.FOOD)
                .with(FoursquareCategoryBuilder.NIGHTLIFE_SPOT)
                .with(FoursquareCategoryBuilder.OUTDOORS_AND_RECREATION)
                .with(FoursquareCategoryBuilder.PROFESSIONAL_AND_OTHER_PLACES)
                .with(FoursquareCategoryBuilder.SHOP_AND_SERVICE)
                .with(FoursquareCategoryBuilder.TRAVEL_AND_TRANSPORT)
                .build();

        Logger.v(TAG, "Foursquare Category Filter - %s", foursquareCategoryFilter);
        params.put(HttpConstants.CATEGORY_ID, foursquareCategoryFilter);
        params.put(HttpConstants.INTENT, HttpConstants.BROWSE);
        params.put(HttpConstants.CLIENT_ID, mFoursquareClientId);
        params.put(HttpConstants.CLIENT_SECRET, mFoursquareClientSecret);
        params.put(HttpConstants.V, FOURSQUARE_API_VERSION);

        request.setParams(params);
        addRequestToQueue(request, true, 0, false);
    }
}
 
Example 13
Source File: HurlStack.java    From TitanjumNote with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 14
Source File: HurlStack.java    From android-common-utils with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
        	//这是不推荐使用的方式,需要向后兼容性处理
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
            //put and post is the same
        case Method.POST:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case Method.PUT:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            addBodyIfExists(connection, request);
            connection.setRequestMethod("PATCH");
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 15
Source File: GosScheduleSiteTool.java    From Gizwits-SmartBuld_Android with MIT License 4 votes vote down vote up
/**
 * <p>
 * Description:
 * </p>
 */
public void getTimeOnSite(final OnResponseGetDeviceDate response) {

	String httpurl = "http://api.gizwits.com/app/scheduler";
	StringRequest stringRequest = new StringRequest(Method.GET, httpurl, new Response.Listener<String>() {
		@Override
		public void onResponse(String arg0) {
			Log.i("onSite", "-------------");
			Log.i("onSite", arg0);
			dataList = new ArrayList<ConcurrentHashMap<String, Object>>();
			try {
				JSONArray js = new JSONArray(arg0);
				for (int i = 0; i < js.length(); i++) {
					JSONObject jo = js.getJSONObject(i);
					ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();
					map.put("date", jo.optString("date"));
					map.put("time", jo.optString("time"));
					map.put("repeat", jo.optString("repeat"));
					map.put("did", getDidFromJsonObject(jo));
					map.put("dataMap", getDateFromJsonObject(jo));
					map.put("ruleID", jo.optString("id"));
					dataList.add(map);
				}
				response.onReceviceDate(dataList);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}, new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			response.onReceviceDate(null);
			error.printStackTrace();
			Log.i("onSite", "获取设备状态请求失败" + error.toString() + error.getNetworkTimeMs());
		}
	}) {

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

	};
	stringRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 4, 0));
	mRequestQueue.add(stringRequest);
}
 
Example 16
Source File: HurlStack.java    From SimplifyReader with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 17
Source File: HurlStack.java    From android-project-wo2b with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 18
Source File: HurlStack.java    From SaveVolley with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        /*
         * 在不明确是 GET 请求,还是 POST 请求的情况下
         * 标识为 Method.DEPRECATED_GET_OR_POST 方法
         * 以下进行了一波判断:request.getPOSTBody() ?
         * 1. request.getPOSTBody()==null 判断为 GET 请求,设置 HttpURLConnection.setRequestMethod("GET")
         * 2. request.getPOSTBody()!=null 判断为 POST 请求,然后进行添加 Content-Type 信息,以及调用
         *    HttpURLConnection 的 OutputStream 去将 请求数据写入
         */
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        // GET 请求,这是请求方法为 "GET"
        case Method.GET:
            // Not necessary to set the request method because connection defaults to GET but
            // being explicit here.
            connection.setRequestMethod("GET");
            break;
        // DELETE 请求,这是请求方法为 "DELETE"
        case Method.DELETE:
            connection.setRequestMethod("DELETE");
            break;
        // POST 请求,这是请求方法为 "POST"
        case Method.POST:
            connection.setRequestMethod("POST");
            // POST 请求需要添加 请求数据
            addBodyIfExists(connection, request);
            break;
        // PUT 请求,这是请求方法为 "PUT"
        case Method.PUT:
            connection.setRequestMethod("PUT");
            // PUT 请求需要添加 请求数据
            addBodyIfExists(connection, request);
            break;
        // HEAD 请求,这是请求方法为 "HEAD"
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        // OPTIONS 请求,这是请求方法为 "OPTIONS"
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        // TRACE 请求,这是请求方法为 "TRACE"
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        // PATCH 请求,这是请求方法为 "PATCH"
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            // PATCH 请求需要添加 请求数据
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 19
Source File: HurlStack.java    From WayHoo with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 20
Source File: HurlStack.java    From volley with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ void setConnectionParametersForRequest(
        HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                connection.setRequestMethod("POST");
                addBody(connection, request, postBody);
            }
            break;
        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;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}