List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:org.mitre.mpf.wfm.rest_client.UnregisterComponent.java
public static void main(String[] args) { String filePath = "/home/mpf/mpf/trunk/java-hello-world/src/main/resources/HelloWorldComponent.json"; //"/home/mpf/mpf/trunk/extraction/hello/cpp/src/helloComponent.json"; String url = "http://localhost:8080/workflow-manager/rest/component/unregisterViaFile"; final String credentials = "Basic bXBmOm1wZjEyMw=="; Map<String, String> params = new HashMap<String, String>(); System.out.println("Starting rest-client!"); //not necessary for localhost //System.setProperty("http.proxyHost","gatekeeper.mitre.org"); //System.setProperty("http.proxyPort","80"); RequestInterceptor authorize = new RequestInterceptor() { @Override// w ww . jav a 2 s . c o m public void intercept(HttpRequestBase request) { request.addHeader("Authorization", credentials); } }; RestClient client = RestClient.builder().requestInterceptor(authorize).build(); if (args.length > 0) { filePath = args[0]; } log.info(filePath); params.put("filePath", filePath); Map<String, String> stringVal = null; try { stringVal = client.get(url, params, Map.class); } catch (RestClientException e) { log.error("RestClientException occurred"); e.printStackTrace(); } catch (IOException e) { log.error("IOException occurred"); e.printStackTrace(); } System.out.println(stringVal.get("message")); }
From source file:org.mitre.mpf.wfm.rest_client.RegisterComponent.java
public static void main(String[] args) { String filePath = "/home/mpf/mpf/trunk/java-hello-world/src/main/resources/HelloWorldComponent.json"; //"/home/mpf/mpf/trunk/extraction/hello/cpp/src/helloComponent.json"; String url = "http://localhost:8080/workflow-manager/rest/component/registerViaFile"; final String credentials = "Basic bXBmOm1wZjEyMw=="; Map<String, String> params = new HashMap<String, String>(); System.out.println("Starting rest-client!"); //not necessary for localhost //System.setProperty("http.proxyHost","gatekeeper.mitre.org"); //System.setProperty("http.proxyPort","80"); RequestInterceptor authorize = new RequestInterceptor() { @Override/*w w w. j a v a 2 s . c o m*/ public void intercept(HttpRequestBase request) { request.addHeader("Authorization", credentials); } }; RestClient client = RestClient.builder().requestInterceptor(authorize).build(); if (args.length > 0) { filePath = args[0]; System.out.println("args[0] = " + args[0]); } params.put("filePath", filePath); Map<String, String> stringVal = null; try { stringVal = client.get(url, params, Map.class); } catch (RestClientException e) { log.error("RestClientException occurred"); e.printStackTrace(); } catch (IOException e) { log.error("IOException occurred"); e.printStackTrace(); } System.out.println(stringVal.get("message")); }
From source file:org.mitre.mpf.rest.client.Main.java
public static void main(String[] args) throws RestClientException, IOException, InterruptedException { System.out.println("Starting rest-client!"); //not necessary for localhost, but left if a proxy configuration is needed //System.setProperty("http.proxyHost",""); //System.setProperty("http.proxyPort",""); String currentDirectory;/* ww w .j a va 2 s . c om*/ currentDirectory = System.getProperty("user.dir"); System.out.println("Current working directory : " + currentDirectory); String username = "mpf"; String password = "mpf123"; byte[] encodedBytes = Base64.encodeBase64((username + ":" + password).getBytes()); String base64 = new String(encodedBytes); System.out.println("encodedBytes " + base64); final String mpfAuth = "Basic " + base64; RequestInterceptor authorize = new RequestInterceptor() { @Override public void intercept(HttpRequestBase request) { request.addHeader("Authorization", mpfAuth /*credentials*/); } }; //RestClient client = RestClient.builder().requestInterceptor(authorize).build(); CustomRestClient client = (CustomRestClient) CustomRestClient.builder() .restClientClass(CustomRestClient.class).requestInterceptor(authorize).build(); //getAvailableWorkPipelineNames String url = "http://localhost:8080/workflow-manager/rest/pipelines"; Map<String, String> params = new HashMap<String, String>(); List<String> availableWorkPipelines = client.get(url, params, new TypeReference<List<String>>() { }); System.out.println("availableWorkPipelines size: " + availableWorkPipelines.size()); System.out.println(Arrays.toString(availableWorkPipelines.toArray())); //processMedia JobCreationRequest jobCreationRequest = new JobCreationRequest(); URI uri = Paths.get(currentDirectory, "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S001-01-t10_01.jpg").toUri(); jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString())); uri = Paths.get(currentDirectory, "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S008-01-t10_01.jpg").toUri(); jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString())); jobCreationRequest.setExternalId("external id"); //get first DLIB pipeline String firstDlibPipeline = availableWorkPipelines.stream() //.peek(pipepline -> System.out.println("will filter - " + pipepline)) .filter(pipepline -> pipepline.startsWith("DLIB")).findFirst().get(); System.out.println("found firstDlibPipeline: " + firstDlibPipeline); jobCreationRequest.setPipelineName(firstDlibPipeline); //grabbed from 'rest/pipelines' - see #1 //two optional params jobCreationRequest.setBuildOutput(true); //jobCreationRequest.setPriority(priority); //will be set to 4 (default) if not set JobCreationResponse jobCreationResponse = client.customPostObject( "http://localhost:8080/workflow-manager/rest/jobs", jobCreationRequest, JobCreationResponse.class); System.out.println("jobCreationResponse job id: " + jobCreationResponse.getJobId()); System.out.println("\n---Sleeping for 10 seconds to let the job process---\n"); Thread.sleep(10000); //getJobStatus url = "http://localhost:8080/workflow-manager/rest/jobs"; // /status"; params = new HashMap<String, String>(); //OPTIONAL //params.put("v", "") - no versioning currently implemented //id is now a path var - if not set, all job info will returned url = url + "/" + Long.toString(jobCreationResponse.getJobId()); SingleJobInfo jobInfo = client.get(url, params, SingleJobInfo.class); System.out.println("jobInfo id: " + jobInfo.getJobId()); //getSerializedOutput String jobIdToGetOutputStr = Long.toString(jobCreationResponse.getJobId()); url = "http://localhost:8080/workflow-manager/rest/jobs/" + jobIdToGetOutputStr + "/output/detection"; params = new HashMap<String, String>(); //REQUIRED - job id is now a path var and required for this endpoint String serializedOutput = client.getAsString(url, params); System.out.println("serializedOutput: " + serializedOutput); }
From source file:com.kolich.http.BlockingTest.java
public static void main(String[] args) { final HttpClient client = getNewInstanceWithProxySelector("foobar"); final Either<Integer, String> result = new HttpClient4Closure<Integer, String>(client) { @Override/*from w ww . j ava2s .c om*/ public void before(final HttpRequestBase request) { request.addHeader("Authorization", "super-secret-password"); } @Override public String success(final HttpSuccess success) throws Exception { return EntityUtils.toString(success.getResponse().getEntity(), UTF_8); } @Override public Integer failure(final HttpFailure failure) { return failure.getStatusCode(); } }.get("http://google.com"); if (result.success()) { System.out.println(result.right()); } else { System.out.println(result.left()); } final Either<Void, Header[]> hResult = new HttpClient4Closure<Void, Header[]>(client) { @Override public Header[] success(final HttpSuccess success) throws Exception { return success.getResponse().getAllHeaders(); } }.head("http://example.com"); if (hResult.success()) { System.out.println("Fetched " + hResult.right().length + " request headers."); } final Either<Void, String> sResult = new StringOrNullClosure(client).get("http://mark.koli.ch"); if (sResult.success()) { System.out.println(sResult.right()); } else { System.out.println(sResult.left()); } final Either<Exception, String> eResult = new HttpClient4Closure<Exception, String>(client) { @Override public String success(final HttpSuccess success) throws Exception { return EntityUtils.toString(success.getResponse().getEntity(), UTF_8); } @Override public Exception failure(final HttpFailure failure) { return failure.getCause(); } }.put("http://lskdjflksdfjslkf.jfjkfhddfgsdfsdf.com"); if (!eResult.success()) { System.out.println(eResult.left()); } // Custom check for "success". final Either<Exception, String> cResult = new HttpClient4Closure<Exception, String>(client) { @Override public boolean check(final HttpResponse response, final HttpContext context) { return (response.getStatusLine().getStatusCode() == 405); } @Override public String success(final HttpSuccess success) throws Exception { return EntityUtils.toString(success.getResponse().getEntity(), UTF_8); } }.put("http://google.com"); if (cResult.success()) { System.out.println(cResult.right()); } final Either<Exception, OutputStream> bResult = new HttpClient4Closure<Exception, OutputStream>(client) { @Override public OutputStream success(final HttpSuccess success) throws Exception { final OutputStream os = new ByteArrayOutputStream(); IOUtils.copy(success.getResponse().getEntity().getContent(), os); return os; } @Override public Exception failure(final HttpFailure failure) { return failure.getCause(); } }.get("http://google.com"); if (bResult.success()) { System.out.println("Loaded bytes into output stream!"); } final OutputStream os = new ByteArrayOutputStream(); final Either<Exception, Integer> stResult = new HttpClient4Closure<Exception, Integer>(client) { @Override public Integer success(final HttpSuccess success) throws Exception { return IOUtils.copy(success.getResponse().getEntity().getContent(), os); } /* @Override public Exception failure(final HttpFailure failure) { return failure.getCause(); } */ }.get("http://mark.koli.ch"); if (stResult.success()) { System.out.println("Loaded " + stResult.right() + " bytes."); } /* final HttpContext context = new BasicHttpContext(); // Setup a basic cookie store so that the response can fetch // any cookies returned by the server in the response. context.setAttribute(COOKIE_STORE, new BasicCookieStore()); final Either<Void,String> cookieResult = new HttpClientClosureExpectString(client) .get(new HttpGet("http://google.com"), context); if(cookieResult.success()) { // List out all cookies that came back from Google in the response. final CookieStore cookies = (CookieStore)context.getAttribute(COOKIE_STORE); for(final Cookie c : cookies.getCookies()) { System.out.println(c.getName() + " -> " + c.getValue()); } }*/ final Either<Integer, List<Cookie>> mmmmm = new HttpClient4Closure<Integer, List<Cookie>>(client) { @Override public void before(final HttpRequestBase request, final HttpContext context) { context.setAttribute(COOKIE_STORE, new BasicCookieStore()); } @Override public List<Cookie> success(final HttpSuccess success) { // Extract a list of cookies from the request. // Might be empty. return ((CookieStore) success.getContext().getAttribute(COOKIE_STORE)).getCookies(); } @Override public Integer failure(final HttpFailure failure) { return failure.getStatusCode(); } }.get("http://google.com"); final List<Cookie> cookies; if ((cookies = mmmmm.right()) != null) { for (final Cookie c : cookies) { System.out.println(c.getName() + " -> " + c.getValue()); } } else { System.out.println("Failed miserably: " + mmmmm.left()); } final Either<Void, Header[]> haResult = new HttpClient4Closure<Void, Header[]>(client) { @Override public Header[] success(final HttpSuccess success) { return success.getResponse().getAllHeaders(); } }.head("http://java.com"); final Header[] headers = haResult.right(); if (headers != null) { for (final Header h : headers) { System.out.println(h.getName() + ": " + h.getValue()); } } }
From source file:org.zywx.wbpalmstar.engine.eservice.EServiceTest.java
public static void test() { String realyPath = "http://localhost:8000/other.QDV"; HttpRequestBase mHhttpRequest = new HttpGet(realyPath); mHhttpRequest.addHeader("range", "bytes=34199-"); BasicHttpParams bparams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(bparams, 20000); HttpConnectionParams.setSoTimeout(bparams, 20000); HttpConnectionParams.setSocketBufferSize(bparams, 8 * 1024); HttpClientParams.setRedirecting(bparams, true); DefaultHttpClient mDefaultHttpClient = new DefaultHttpClient(bparams); HttpResponse response = null;/*from w w w .ja v a2 s . c o m*/ try { response = mDefaultHttpClient.execute(mHhttpRequest); int responseCode = response.getStatusLine().getStatusCode(); byte[] arrayOfByte = null; HttpEntity httpEntity = response.getEntity(); if (responseCode == 200 || responseCode == 206) { arrayOfByte = toByteArray(httpEntity); String m = new String(arrayOfByte, "UTF-8"); Log.i("ldx", "" + m.length()); Log.i("ldx", m); return; } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java
public static JsonObject getGsonResponse(CloseableHttpClient httpClient, HttpRequestBase request) throws IOException, ClientProtocolException { request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); CloseableHttpResponse response = httpClient.execute(request); JsonObject jsonResponse;/* w w w .j av a 2s . c om*/ try { HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { final String errorInfo; if (entity != null) errorInfo = " -- " + EntityUtils.toString(entity); else errorInfo = ""; throw new IllegalStateException( "Unexpected HTTP resource from service:" + response.getStatusLine().getStatusCode() + ":" + response.getStatusLine().getReasonPhrase() + errorInfo); } if (entity == null) throw new IllegalStateException("No HTTP resource from service"); Reader r = new InputStreamReader(entity.getContent()); jsonResponse = new Gson().fromJson(r, JsonObject.class); EntityUtils.consume(entity); } finally { response.close(); } return jsonResponse; }
From source file:org.freaknet.gtrends.api.GoogleUtils.java
/** * Setup the <code>HttpRequestBase</code> r with default headers and HTTP * parameters./*from w ww.j a v a2 s. c om*/ * * @param r <code>HttpRequestBase</code> to setup * @throws org.apache.commons.configuration.ConfigurationException */ public static void setupHttpRequestDefaults(HttpRequestBase r) throws ConfigurationException { DataConfiguration config = GoogleConfigurator.getConfiguration(); //r.addHeader("Content-type", config.getString("request.default.content-type")); r.addHeader("User-Agent", config.getString("request.default.user-agent")); r.addHeader("Accept", config.getString("request.default.accept")); r.addHeader("Accept-Language", config.getString("request.default.accept-language")); r.addHeader("Accept-Encoding", config.getString("request.default.accept-encoding")); r.addHeader("Connection", config.getString("request.default.connection")); }
From source file:com.appunite.socketio.helpers.HTTPUtils.java
/** * Add standard headers to response.//from www . j ava2 s. c om * * initialize Accept-Language by current locale setup Accept-Encoding to * gzip * * @param request * request to witch should be added headers */ public static void setupDefaultHeaders(HttpRequestBase request) { setLangageForHttpRequest(request); request.addHeader("Accept-Encoding", "gzip"); }
From source file:com.bjorsond.android.timeline.sync.ServerUploader.java
/** * Sets the content header of the HTTP request to send and accept JSON. * //from w w w . j a va2s . c o m * @param httpRequest The {@link HttpRequest} to add headers. */ private static void makeJSONHttpRequestContentTypeHeader(HttpRequestBase httpRequest) { // Make sure the server knows what kind of a response we will accept httpRequest.addHeader("Accept", "application/json"); // Also be sure to tell the server what kind of content we are sending httpRequest.addHeader("Content-Type", "application/json"); // httpRequest.addHeader(CoreProtocolPNames.USER_AGENT, "TimelineAndroid"); }
From source file:org.anhonesteffort.flock.registration.RegistrationApi.java
private static void authorizeRequest(HttpRequestBase httpRequest, DavAccount account) { String encodedAuth = account.getUserId() + ":" + account.getAuthToken(); httpRequest.addHeader("Authorization", "Basic " + Base64.encodeBytes(encodedAuth.getBytes())); }