List of usage examples for org.apache.http.client.methods HttpGet METHOD_NAME
String METHOD_NAME
To view the source code for org.apache.http.client.methods HttpGet METHOD_NAME.
Click Source Link
From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java
private TestCase createHttpContentApiTest(final DataFormat inputFormat, final DataFormat outputFormat, final Random rndGen) { String name = String.format("HttpContent Overload - Input: %s - Output: %s", inputFormat, outputFormat); TestCase test = new TestCase(name) { private static final String TEST_HEADER_PREFIX = "x-test-zumo-"; MobileServiceClient mClient;//from w w w .jav a 2 s . c o m List<Pair<String, String>> mQuery; List<Pair<String, String>> mHeaders; TestExecutionCallback mCallback; JsonObject mExpectedResult; int mExpectedStatusCode; String mHttpMethod; byte[] mContent; TestResult mResult; @Override protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) { mResult = new TestResult(); mResult.setTestCase(this); mResult.setStatus(TestStatus.Passed); mClient = client; mCallback = callback; mHeaders = new ArrayList<Pair<String, String>>(); createHttpContentTestInput(inputFormat, outputFormat, rndGen); try { ServiceFilterResponse response = mClient .invokeApi(APP_API_NAME, mContent, mHttpMethod, mHeaders, mQuery).get(); Exception ex = validateResponseHeaders(response); if (ex != null) { createResultFromException(mResult, ex); } else { mResult.getTestCase().log("Header validated successfully"); String responseContent = response.getContent(); mResult.getTestCase().log("Response content: " + responseContent); JsonElement jsonResponse = null; if (outputFormat == DataFormat.Json) { jsonResponse = new JsonParser().parse(responseContent); } else if (outputFormat == DataFormat.Other) { String decodedContent = responseContent.replace("__{__", "{").replace("__}__", "}") .replace("__[__", "[").replace("__]__", "]"); jsonResponse = new JsonParser().parse(decodedContent); } switch (outputFormat) { case Json: case Other: if (!Util.compareJson(mExpectedResult, jsonResponse)) { createResultFromException(mResult, new ExpectedValueException(mExpectedResult, jsonResponse)); } break; default: String expectedResultContent = jsonToXml(mExpectedResult); // Normalize CRLF expectedResultContent = expectedResultContent.replace("\r\n", "\n"); responseContent = responseContent.replace("\r\n", "\n"); if (!expectedResultContent.equals(responseContent)) { createResultFromException(mResult, new ExpectedValueException(expectedResultContent, responseContent)); } break; } } } catch (Exception exception) { createResultFromException(exception); mCallback.onTestComplete(mResult.getTestCase(), mResult); return; } mCallback.onTestComplete(mResult.getTestCase(), mResult); } private Exception validateResponseHeaders(ServiceFilterResponse response) { if (mExpectedStatusCode != response.getStatus().getStatusCode()) { mResult.getTestCase().log("Invalid status code"); String content = response.getContent(); if (content != null) { mResult.getTestCase().log("Response: " + content); } return new ExpectedValueException(mExpectedStatusCode, response.getStatus().getStatusCode()); } else { for (Pair<String, String> header : mHeaders) { if (header.first.startsWith(TEST_HEADER_PREFIX)) { if (!Util.responseContainsHeader(response, header.first)) { mResult.getTestCase().log("Header " + header.first + " not found"); return new ExpectedValueException("Header: " + header.first, ""); } else { String headerValue = Util.getHeaderValue(response, header.first); if (!header.second.equals(headerValue)) { mResult.getTestCase().log("Invalid Header value for " + header.first); return new ExpectedValueException(header.second, headerValue); } } } } } return null; } private void createHttpContentTestInput(DataFormat inputFormat, DataFormat outputFormat, Random rndGen) { mHttpMethod = createHttpMethod(rndGen); log("Method = " + mHttpMethod); mExpectedResult = new JsonObject(); mExpectedResult.addProperty("method", mHttpMethod); JsonObject user = new JsonObject(); user.addProperty("level", "anonymous"); mExpectedResult.add("user", user); JsonElement body = null; String textBody = null; if (!mHttpMethod.equals(HttpGet.METHOD_NAME) && !mHttpMethod.equals(HttpDelete.METHOD_NAME)) { body = createJson(rndGen, 0, true); if (outputFormat == DataFormat.Xml || inputFormat == DataFormat.Xml) { // to prevent non-XML names from interfering with checks body = sanitizeJsonXml(body); } try { switch (inputFormat) { case Json: mContent = body.toString().getBytes("utf-8"); mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "application/json")); break; case Xml: textBody = jsonToXml(body); mContent = textBody.getBytes("utf-8"); mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/xml")); break; default: textBody = body.toString().replace('{', '<').replace('}', '>').replace("[", "__[__") .replace("]", "__]__"); mContent = textBody.getBytes("utf-8"); mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/plain")); break; } } catch (UnsupportedEncodingException e) { // this will never happen } } if (body != null) { if (inputFormat == DataFormat.Json) { mExpectedResult.add("body", body); } else { mExpectedResult.addProperty("body", textBody); } } int choice = rndGen.nextInt(5); for (int j = 0; j < choice; j++) { String name = TEST_HEADER_PREFIX + j; String value = Util.createSimpleRandomString(rndGen, rndGen.nextInt(10) + 1, 'a', 'z'); mHeaders.add(new Pair<String, String>(name, value)); } mQuery = createQuery(rndGen); if (mQuery == null) { mQuery = new ArrayList<Pair<String, String>>(); } if (mQuery.size() > 0) { JsonObject outputQuery = new JsonObject(); for (Pair<String, String> element : mQuery) { outputQuery.addProperty(element.first, element.second); } mExpectedResult.add("query", outputQuery); } mQuery.add(new Pair<String, String>("format", outputFormat.toString().toLowerCase(Locale.getDefault()))); mExpectedStatusCode = 200; if (rndGen.nextInt(4) == 0) { // non-200 responses int[] options = new int[] { 400, 404, 500, 201 }; int status = options[rndGen.nextInt(options.length)]; mExpectedStatusCode = status; mQuery.add(new Pair<String, String>("status", Integer.valueOf(status).toString())); } } private String jsonToXml(JsonElement json) { StringBuilder sb = new StringBuilder(); sb.append("<root>"); jsonToXml(json, sb); sb.append("</root>"); return sb.toString(); } private void jsonToXml(JsonElement json, StringBuilder sb) { if (json == null) { json = new JsonPrimitive(""); } if (json.isJsonNull()) { sb.append("null"); } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean()) { sb.append(json.toString().toLowerCase(Locale.getDefault())); } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) { sb.append(json.toString()); } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) { sb.append(json.getAsJsonPrimitive().getAsString()); } else if (json.isJsonArray()) { sb.append("<array>"); JsonArray array = json.getAsJsonArray(); for (int i = 0; i < array.size(); i++) { sb.append("<item>"); jsonToXml(array.get(i), sb); sb.append("</item>"); } sb.append("</array>"); } else { Set<Entry<String, JsonElement>> entrySet = json.getAsJsonObject().entrySet(); List<String> keys = new ArrayList<String>(); for (Entry<String, JsonElement> entry : entrySet) { keys.add(entry.getKey()); } Collections.sort(keys); for (String key : keys) { sb.append("<" + key + ">"); jsonToXml(json.getAsJsonObject().get(key), sb); sb.append("</" + key + ">"); } } } private JsonElement sanitizeJsonXml(JsonElement body) { if (body.isJsonArray()) { JsonArray array = new JsonArray(); for (JsonElement element : body.getAsJsonArray()) { array.add(sanitizeJsonXml(element)); } return array; } else if (body.isJsonObject()) { JsonObject object = new JsonObject(); Set<Entry<String, JsonElement>> entrySet = body.getAsJsonObject().entrySet(); int i = 0; for (Entry<String, JsonElement> entry : entrySet) { object.add("memeber" + i, sanitizeJsonXml(entry.getValue())); i++; } return object; } else { return body; } } }; return test; }
From source file:com.mirth.connect.client.core.ServerConnection.java
private HttpRequestBase createRequestBase(String method) { HttpRequestBase requestBase = null;// ww w.j av a 2 s . c o m if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) { requestBase = new HttpGet(); } else if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) { requestBase = new HttpPost(); } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) { requestBase = new HttpPut(); } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) { requestBase = new HttpDelete(); } else if (StringUtils.equalsIgnoreCase(HttpOptions.METHOD_NAME, method)) { requestBase = new HttpOptions(); } else if (StringUtils.equalsIgnoreCase(HttpPatch.METHOD_NAME, method)) { requestBase = new HttpPatch(); } requestBase.setConfig(requestConfig); return requestBase; }
From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java
/** * Returns the request that points to the backend service defined by the provided * <code>urlToService</code> URL. The headers of the origin request are copied to * the backend request, except of "host" and "content-length". * /* w w w . j a v a2s. c o m*/ * @param request * original request to the Web application * @param urlToService * URL to the targeted backend service * @return initialized backend service request * @throws IOException */ private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException { String method = request.getMethod(); LOGGER.debug("HTTP method: " + method); HttpRequestBase backendRequest = null; if (HttpPost.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPost post = new HttpPost(urlToService); post.setEntity(entity); backendRequest = post; } else if (HttpGet.METHOD_NAME.equals(method)) { HttpGet get = new HttpGet(urlToService); backendRequest = get; } else if (HttpPut.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPut put = new HttpPut(urlToService); put.setEntity(entity); backendRequest = put; } else if (HttpDelete.METHOD_NAME.equals(method)) { HttpDelete delete = new HttpDelete(urlToService); backendRequest = delete; } // copy headers from Web application request to backend request, while // filtering the blocked headers LOGGER.debug("backend request headers:"); Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS)); Enumeration<String> setCookieHeaders = request.getHeaders("Cookie"); while (setCookieHeaders.hasMoreElements()) { String cookieHeader = setCookieHeaders.nextElement(); if (blockedHeaders.contains(cookieHeader.toLowerCase())) { String replacedCookie = removeJSessionID(cookieHeader); backendRequest.addHeader("Cookie", replacedCookie); } LOGGER.debug("Cookie header => " + cookieHeader); } for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); if (!blockedHeaders.contains(headerName.toLowerCase())) { backendRequest.addHeader(headerName, request.getHeader(headerName)); LOGGER.debug(" => " + headerName + ": " + request.getHeader(headerName)); } else { LOGGER.debug(" => " + headerName + ": blocked request header"); } } return backendRequest; }
From source file:com.azure.webapi.MobileServiceClient.java
/** * /*from w ww .ja va2 s . com*/ * @param apiName * The API name * @param content * The byte array to send as the request body * @param httpMethod * The HTTP Method used to invoke the API * @param requestHeaders * The extra headers to send in the request * @param parameters * The query string parameters sent in the request * @param callback * The callback to invoke after the API execution */ public void invokeApi(String apiName, byte[] content, String httpMethod, List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters, final ServiceFilterResponseCallback callback) { if (apiName == null || apiName.trim().equals("")) { if (callback != null) { callback.onResponse(null, new IllegalArgumentException("apiName cannot be null")); } return; } if (httpMethod == null || httpMethod.trim().equals("")) { if (callback != null) { callback.onResponse(null, new IllegalArgumentException("httpMethod cannot be null")); } return; } Uri.Builder uriBuilder = Uri.parse(getAppUrl().toString()).buildUpon(); uriBuilder.path(CUSTOM_API_URL + apiName); if (parameters != null && parameters.size() > 0) { for (Pair<String, String> parameter : parameters) { uriBuilder.appendQueryParameter(parameter.first, parameter.second); } } ServiceFilterRequest request; String url = uriBuilder.build().toString(); if (httpMethod.equalsIgnoreCase(HttpGet.METHOD_NAME)) { request = new ServiceFilterRequestImpl(new HttpGet(url)); } else if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) { request = new ServiceFilterRequestImpl(new HttpPost(url)); } else if (httpMethod.equalsIgnoreCase(HttpPut.METHOD_NAME)) { request = new ServiceFilterRequestImpl(new HttpPut(url)); } else if (httpMethod.equalsIgnoreCase(HttpPatch.METHOD_NAME)) { request = new ServiceFilterRequestImpl(new HttpPatch(url)); } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { request = new ServiceFilterRequestImpl(new HttpDelete(url)); } else { if (callback != null) { callback.onResponse(null, new IllegalArgumentException("httpMethod not supported")); } return; } if (requestHeaders != null && requestHeaders.size() > 0) { for (Pair<String, String> header : requestHeaders) { request.addHeader(header.first, header.second); } } if (content != null) { try { request.setContent(content); } catch (Exception e) { if (callback != null) { callback.onResponse(null, e); } return; } } MobileServiceConnection conn = createConnection(); // Create AsyncTask to execute the request and parse the results new RequestAsyncTask(request, conn) { @Override protected void onPostExecute(ServiceFilterResponse response) { if (callback != null) { callback.onResponse(response, mTaskException); } } }.execute(); }
From source file:com.ubuntuone.android.files.provider.MetaUtilities.java
public static int resetFailedTransfers() { int failed = 0; failed += resetFailedTransfers(HttpPost.METHOD_NAME); failed += resetFailedTransfers(HttpGet.METHOD_NAME); return failed; }
From source file:com.ubuntuone.android.files.provider.MetaUtilities.java
public static int resetFailedTransfers(String method) { String ongoing;/*from w ww . ja v a2 s .c o m*/ String failed; if (HttpPost.METHOD_NAME.equals(method)) { ongoing = ResourceState.STATE_POSTING; failed = ResourceState.STATE_POSTING_FAILED; } else if (HttpGet.METHOD_NAME.equals(method)) { ongoing = ResourceState.STATE_GETTING; failed = ResourceState.STATE_GETTING_FAILED; } else { Log.e(TAG, "Bad method name: " + method); return 0; } final ContentValues values = new ContentValues(1); values.put(Nodes.NODE_RESOURCE_STATE, failed); final String where = Nodes.NODE_RESOURCE_STATE + "=?"; final String[] selectionArgs = new String[] { ongoing }; return sResolver.update(Nodes.CONTENT_URI, values, where, selectionArgs); }
From source file:org.trancecode.xproc.step.RequestParser.java
private HttpRequestBase constructMethod(final String method, final URI hrefUri) { final HttpEntity httpEntity = request.getEntity(); final HeaderGroup headers = request.getHeaders(); if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) { final HttpPost httpPost = new HttpPost(hrefUri); for (final Header h : headers.getAllHeaders()) { if (!StringUtils.equalsIgnoreCase("Content-Type", h.getName())) { httpPost.addHeader(h);/*from www. j a v a 2 s . c om*/ } } httpPost.setEntity(httpEntity); return httpPost; } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) { final HttpPut httpPut = new HttpPut(hrefUri); httpPut.setEntity(httpEntity); return httpPut; } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) { final HttpDelete httpDelete = new HttpDelete(hrefUri); httpDelete.setHeaders(headers.getAllHeaders()); return httpDelete; } else if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) { final HttpGet httpGet = new HttpGet(hrefUri); httpGet.setHeaders(headers.getAllHeaders()); return httpGet; } else if (StringUtils.equalsIgnoreCase(HttpHead.METHOD_NAME, method)) { final HttpHead httpHead = new HttpHead(hrefUri); httpHead.setHeaders(headers.getAllHeaders()); return httpHead; } return null; }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
private static void assertResourceOptionsHeaders(final HttpResponse httpResponse) { final List<String> methods = headerValues(httpResponse, "Allow"); assertTrue("Should allow GET", methods.contains(HttpGet.METHOD_NAME)); assertTrue("Should allow PUT", methods.contains(HttpPut.METHOD_NAME)); assertTrue("Should allow DELETE", methods.contains(HttpDelete.METHOD_NAME)); assertTrue("Should allow OPTIONS", methods.contains(HttpOptions.METHOD_NAME)); }
From source file:com.joyent.manta.http.StandardHttpHelper.java
/** * Attempts to construct a {@link InputStreamContinuator} for the initial request-response exchange. If the request * cannot be resumed (either because the exchange is malformed or the request does not support resuming) we will * return null, otherwise the continuator receives our client, the initial request (which it will clone) and the * marker we created.//from ww w. j a v a 2s.com * * @see HttpDownloadContinuationMarker#validateInitialExchange * * @param request the initial request, etag and range headers will be used as hints for the first argument to * {@link HttpDownloadContinuationMarker#validateInitialExchange(Pair, int, Pair)} * @param response the initial response which will be validated against any hints * @return the continuator which can be used to resume this request */ private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request, final CloseableHttpResponse response) { if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod()) || !(this.connectionContext instanceof MantaApacheHttpClientContext) || !(request instanceof HttpGet)) { return null; } final HttpGet get = (HttpGet) request; final HttpDownloadContinuationMarker marker; try { // if we can't build a marker the request: // - uses a combination of headers we don't support (e.g. multi-part range) // - the request/response pair exhibits unexpected behavior we are not prepared to follow marker = validateInitialExchange(extractDownloadRequestFingerprint(get), response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true)); } catch (final ProtocolException pe) { LOGGER.debug("HTTP download cannot be automatically continued: {}", pe.getMessage()); return null; } try { return new ApacheHttpGetResponseEntityContentContinuator( (MantaApacheHttpClientContext) this.connectionContext, get, marker, this.maxDownloadContinuations); } catch (final HttpDownloadContinuationException rde) { LOGGER.debug(String.format("Expected to build a continuator but an exception occurred: %s", rde.getMessage())); } return null; }
From source file:org.elasticsearch.client.RequestConverters.java
static Request get(GetRequest getRequest) { return getStyleRequest(HttpGet.METHOD_NAME, getRequest); }