public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() != null || authState.hasAuthOptions()) { return; } // If no authState has been established and this is a PUT or POST request, add preemptive authorisation String requestMethod = request.getRequestLine().getMethod(); if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (credentials == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, credentials); } }
private HttpRequestBase getRequest(String url){ switch(method){ case DELETE: return new HttpDelete(url); case GET: return new HttpGet(url); case HEAD: return new HttpHead(url); case PATCH: return new HttpPatch(url); case POST: return new HttpPost(url); case PUT: return new HttpPut(url); default: throw new IllegalArgumentException("Invalid or null HttpMethod: " + method); } }
private HttpRequestBase createApacheRequest(SdkHttpFullRequest request, String uri) { switch (request.method()) { case HEAD: return new HttpHead(uri); case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case PATCH: return wrapEntity(request, new HttpPatch(uri)); case POST: return wrapEntity(request, new HttpPost(uri)); case PUT: return wrapEntity(request, new HttpPut(uri)); default: throw new RuntimeException("Unknown HTTP method name: " + request.method()); } }
/** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); }
/** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); }
/** * * @param payload * @return */ protected HttpPut createPutRequest(final Object value, final String collection) { try { logger.debug("received value {}, and collection {}", value, collection); final Map<?, ?> valueMap = new LinkedHashMap<>((Map<?,?>)value); final Object url = valueMap.remove(URL); final URIBuilder uriBuilder = getURIBuilder(null == url ? UUID.randomUUID().toString() : url.toString(), collection); final String jsonString = MAPPER.writeValueAsString(valueMap); final HttpPut request = new HttpPut(uriBuilder.build()); final StringEntity params = new StringEntity(jsonString, "UTF-8"); params.setContentType(DEFAULT_CONTENT_TYPE.toString()); request.setEntity(params); return request; } catch (URISyntaxException | JsonProcessingException | MalformedURLException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } }
@Override public <REQ> CloseableHttpResponse sendHttpPut(String url, REQ request) { CloseableHttpResponse execute = null; String requestJson = GsonUtils.toJson(request); try { LOGGER.log(Level.FINER, "Send PUT request:" + requestJson + " to url-" + url); HttpPut httpPut = new HttpPut(url); StringEntity entity = new StringEntity(requestJson, "UTF-8"); entity.setContentType("application/json"); httpPut.setEntity(entity); execute = this.httpClientFactory.getHttpClient().execute(httpPut); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Was unable to send PUT request:" + requestJson + " (displaying first 1000 chars) from url-" + url, e); } return execute; }
static Request index(IndexRequest indexRequest) { String method = Strings.hasLength(indexRequest.id()) ? HttpPut.METHOD_NAME : HttpPost.METHOD_NAME; boolean isCreate = (indexRequest.opType() == DocWriteRequest.OpType.CREATE); String endpoint = endpoint(indexRequest.index(), indexRequest.type(), indexRequest.id(), isCreate ? "_create" : null); Params parameters = Params.builder(); parameters.withRouting(indexRequest.routing()); parameters.withParent(indexRequest.parent()); parameters.withTimeout(indexRequest.timeout()); parameters.withVersion(indexRequest.version()); parameters.withVersionType(indexRequest.versionType()); parameters.withPipeline(indexRequest.getPipeline()); parameters.withRefreshPolicy(indexRequest.getRefreshPolicy()); parameters.withWaitForActiveShards(indexRequest.waitForActiveShards()); BytesRef source = indexRequest.source().toBytesRef(); ContentType contentType = ContentType.create(indexRequest.getContentType().mediaType()); HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, contentType); return new Request(method, endpoint, parameters.getParams(), entity); }
private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) { switch(method.toUpperCase(Locale.ROOT)) { case HttpDeleteWithEntity.METHOD_NAME: return addRequestBody(new HttpDeleteWithEntity(uri), entity); case HttpGetWithEntity.METHOD_NAME: return addRequestBody(new HttpGetWithEntity(uri), entity); case HttpHead.METHOD_NAME: return addRequestBody(new HttpHead(uri), entity); case HttpOptions.METHOD_NAME: return addRequestBody(new HttpOptions(uri), entity); case HttpPatch.METHOD_NAME: return addRequestBody(new HttpPatch(uri), entity); case HttpPost.METHOD_NAME: HttpPost httpPost = new HttpPost(uri); addRequestBody(httpPost, entity); return httpPost; case HttpPut.METHOD_NAME: return addRequestBody(new HttpPut(uri), entity); case HttpTrace.METHOD_NAME: return addRequestBody(new HttpTrace(uri), entity); default: throw new UnsupportedOperationException("http method not supported: " + method); } }
/** * Returns the supported http methods given the rest parameters provided */ public List<String> getSupportedMethods(Set<String> restParams) { //we try to avoid hardcoded mappings but the index api is the exception if ("index".equals(name) || "create".equals(name)) { List<String> indexMethods = new ArrayList<>(); for (String method : methods) { if (restParams.contains("id")) { //PUT when the id is provided if (HttpPut.METHOD_NAME.equals(method)) { indexMethods.add(method); } } else { //POST without id if (HttpPost.METHOD_NAME.equals(method)) { indexMethods.add(method); } } } return indexMethods; } return methods; }
/** * sendPutCommand * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPutCommand(String url, Map<String, Object> credentials, Map<String, String> parameters) throws ManagerResponseException { Map<String, Object> response = new HashMap<String, Object>(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-type", "application/json"); try { ObjectMapper mapper = new ObjectMapper(); StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters)); httpPut.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPut, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { throw new ManagerResponseException(e.getMessage(), e); } return response; }
public IndexResponse execute() { final HttpClient client = wrapper.getHttpClient(); IndexResponse indexResponse = null; try { final HttpPut httpPut = new HttpPut(this.path); httpPut.setEntity(new StringEntity(this.data.toString(), ContentType.APPLICATION_JSON)); System.out.println(this.data.toString()); indexResponse = client.execute(httpPut, new IndexResponseHandler()); } catch (IOException ioe) { //TODO: Tham } return indexResponse; }
public boolean writeA(String key,String[] all_data) { try { StringBuffer sb = new StringBuffer(); sb.append("{"+QUATA+key+QUATA+":["); for (String i : all_data) { sb.append(QUATA+i+QUATA+","); } String data = sb.toString(); data = data.substring(0, data.length() - 1); String node = data + "]}"; HttpClient httpclient = HttpClients.createDefault(); HttpPut httppost = new HttpPut(getChannelUrl()); // Use PUT prevents key generation for each as a parent StringEntity entity = new StringEntity(node); httppost.setEntity(entity); httppost.setHeader("Accept", "application/json"); httppost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httppost); this.resetChannel(); return response.getStatusLine().getStatusCode() == 200; } catch (Exception ex) { ex.printStackTrace(); return false; } }
private Map put(String url, String data) throws IOException, HttpException { Map<String,Object> map = null; CredentialsProvider credentials = credentialsProvider(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentials) .build(); try { HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-Type", "application/json"); HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8")); httpPut.setEntity(entity); System.out.println("Executing request " + httpPut.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPut); try { LOG.debug("----------------------------------------"); LOG.debug((String)response.getStatusLine().getReasonPhrase()); String responseBody = EntityUtils.toString(response.getEntity()); LOG.debug(responseBody); Gson gson = new Gson(); map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass()); LOG.debug(responseBody); } finally { response.close(); } } finally { httpclient.close(); } return map; }
private JsonObject sendPut(String domain, URI target, JsonObject payload) { String authObj = getAuthObj(domain, "PUT", target, payload); String sign = global.getSignMgr().sign(authObj); String key = "ed25519:" + global.getKeyMgr().getCurrentIndex(); HttpPut req = new HttpPut(target); req.setEntity(getJsonEntity(payload)); req.setHeader("Host", domain); req.setHeader("Authorization", "X-Matrix origin=" + global.getDomain() + ",key=\"" + key + "\",sig=\"" + sign + "\""); log.info("Calling [{}] {}", domain, req); try (CloseableHttpResponse res = client.execute(req)) { int resStatus = res.getStatusLine().getStatusCode(); JsonObject body = getBody(res.getEntity()); if (resStatus == 200) { log.info("Got answer"); return body; } else { throw new FederationException(resStatus, body); } } catch (IOException e) { throw new RuntimeException(e); } }
/** * Put String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); }
/** * Put stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); }
protected ObjectNode putItemError(String itemUri, String json, String token, int responseCode, Object... paramNameValues) throws Exception { final HttpPut request = new HttpPut(appendQueryString(itemUri, queryString(paramNameValues))); final StringEntity ent = new StringEntity(json, "UTF-8"); ent.setContentType("application/json"); request.setEntity(ent); HttpResponse response = execute(request, false, token); try { assertResponse(response, responseCode, "Incorrect response code"); ObjectNode error = (ObjectNode) mapper.readTree(response.getEntity().getContent()); return error; } finally { EntityUtils.consume(response.getEntity()); } }
/** * Create a Commons HttpMethodBase object for the given HTTP method and URI specification. * @param httpMethod the HTTP method * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { switch (httpMethod) { case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case HEAD: return new HttpHead(uri); case OPTIONS: return new HttpOptions(uri); case POST: return new HttpPost(uri); case PUT: return new HttpPut(uri); case TRACE: return new HttpTrace(uri); case PATCH: return new HttpPatch(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
public static void loadBug18993(){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8011), new UsernamePasswordCredentials("admin", "admin")); String document ="<foo>a space b</foo>"; String perm = "perm:rest-writer=read&perm:rest-writer=insert&perm:rest-writer=update&perm:rest-writer=execute"; HttpPut put = new HttpPut("http://"+host+":8011/v1/documents?uri=/a%20b&"+perm); put.addHeader("Content-type", "application/xml"); put.setEntity(new StringEntity(document)); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"authentication\": \""+level+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"default-user\": \""+usr+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException { try { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(jnode.toString())); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
/** * Realiza a adição ou edição da URL que deve ser utilizada pelos webhooks da Conta Digital * @param url: URL à ser configurada como Webhook * @return boolean */ public boolean manageWebhookURL(String url) throws IOException, PJBankException { PJBankClient client = new PJBankClient(this.endPoint); HttpPut httpPut = client.getHttpPutClient(); httpPut.addHeader("x-chave-conta", this.chave); JSONObject params = new JSONObject(); params.put("webhook", url); httpPut.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8)); String response = EntityUtils.toString(client.doRequest(httpPut).getEntity()); JSONObject responseObject = new JSONObject(response); return url.equals(responseObject.getString("webhook")); }
@Override public int runCommand() { try { String url = serverParameters.getServerUrl() + getRequestUrl(); URIBuilder builder = new URIBuilder(String.format(url, datasetId)); if (parentId != null) { builder.addParameter("parentId", String.valueOf(parentId)); } HttpPut put = new HttpPut(builder.build()); setDefaultHeader(put); if (isSecure()) { addAuthorizationToRequest(put); } RequestManager.executeRequest(put); } catch (URISyntaxException e) { throw new ApplicationException(e.getMessage(), e); } return 0; }
/** * HTTP PUT字节数组 * @param host * @param path * @param connectTimeout * @param headers * @param querys * @param bodys * @param signHeaderPrefixList * @param appKey * @param appSecret * @return * @throws Exception */ public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret) throws Exception { headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret); HttpClient httpClient = wrapClient(host); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout)); HttpPut put = new HttpPut(initUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue())); } if (bodys != null) { put.setEntity(new ByteArrayEntity(bodys)); } return convert(httpClient.execute(put)); }
private HttpUtils(HttpRequestBase request) { this.request = request; this.clientBuilder = HttpClientBuilder.create(); this.isHttps = request.getURI().getScheme().equalsIgnoreCase("https"); this.config = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); this.cookieStore = new BasicCookieStore(); if (request instanceof HttpPost) { this.type = 1; this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>()); } else if (request instanceof HttpGet) { this.type = 2; this.uriBuilder = new URIBuilder(); } else if (request instanceof HttpPut) { this.type = 3; this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>()); } else if (request instanceof HttpDelete) { this.type = 4; this.uriBuilder = new URIBuilder(); } }
/** * Updates the module * * @param moduleName * the name of the module to add * @param objectToUpdate * JSON containing the key/value pais to use for update * @return request object to check status codes and return values */ public Response updateModule( String moduleName, JSONObject objectToUpdate ) { HttpPut request = new HttpPut( this.yambasBase + "modules/" + moduleName ); setAuthorizationHeader( request ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); request.setEntity( new StringEntity( objectToUpdate.toString( ), ContentType.APPLICATION_JSON ) ); try { final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
/** * Sets the app to active state * * @param customerName * the name of the customer * @param appName * the name of the app * @return request object to check status codes and return values */ public Response deployApp( String customerName, String appName ) { HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName ); setAuthorizationHeader( request ); request.addHeader( "ContentType", "application/json" ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); try { final HttpEntity requestEntity = new StringEntity( "{\"applicationStatus\":{\"" + this.system + "\":\"ACTIVE\"}, \"applicationName\":\"" + appName + "\"}", ContentType.APPLICATION_JSON ); request.setEntity( requestEntity ); final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
/** * Updates a modules config for the given app * * @param customerName * the name of the customer * @param appName * the name of the app * @param moduleName * the name of the module to update config for * @param key * config key * @param value * value of the config * @return request object to check status codes and return values */ public Response updateConfig( String customerName, String appName, String moduleName, String key, String value ) { final HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName ); setAuthorizationHeader( request ); request.addHeader( "ContentType", "application/json" ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); try { final HttpEntity requestEntity = new StringEntity( "{\"configuration\":" + " {\"" + this.system.toString( ).toLowerCase( ) + "Config\": {\"" + moduleName + "\":{\"" + key + "\":\"" + value + "\"}}}, \"applicationName\":\"" + appName + "\"}", ContentType.APPLICATION_JSON ); request.setEntity( requestEntity ); final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
public void upload(LocalResource resource, URI destination) throws IOException { HttpPut method = new HttpPut(destination); final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(resource, ContentType.APPLICATION_OCTET_STREAM); method.setEntity(entity); CloseableHttpResponse response = null; try { response = http.performHttpRequest(method); if (!http.wasSuccessful(response)) { throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s", destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } finally { HttpClientUtils.closeQuietly(response); } }
@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); }
@Test public void createPutRequestWithBody() throws Exception { TestRequest.PutWithBody request = new TestRequest.PutWithBody(); assertEquals(request.getMethod(), Method.PUT); HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null); assertTrue(httpRequest instanceof HttpPut); }
@Test public void putEmptyEntity() throws Exception { server.enqueue(new MockResponse()); final HttpPut put = new HttpPut(server.url("/").url().toURI()); client.execute(put); RecordedRequest request = server.takeRequest(); assertEquals(0, request.getBodySize()); assertNotNull(request.getBody()); }
public HttpPut createPut(String url, final List<NameValuePair> params, ApplicationType accept) throws IOException { HttpPut method = new HttpPut(url); if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, reqCharset); method.setEntity(entity); } if (null != accept) { method.addHeader("accept", accept.val()); } return method; }