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.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext/*from w w w . j av a2 s . c om*/ * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }
From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestClient.java
private static boolean sendBodyAsSourceParam(List<String> supportedMethods, String contentType) { if (supportedMethods.contains(HttpGet.METHOD_NAME)) { if (contentType.startsWith(ContentType.APPLICATION_JSON.getMimeType()) || contentType.startsWith(YAML_CONTENT_TYPE.getMimeType())) { return RandomizedTest.rarely(); }/*from w w w . jav a2s .c o m*/ } return false; }
From source file:com.uploader.Vimeo.java
public VimeoResponse getTextTracks(String videoEndPoint) throws IOException { return apiRequest(new StringBuffer(videoEndPoint).append("/texttracks").toString(), HttpGet.METHOD_NAME, null, null);/* ww w. jav a 2 s . c o m*/ }
From source file:com.uploader.Vimeo.java
public VimeoResponse getTextTrack(String videoEndPoint, String textTrackId) throws IOException { return apiRequest(new StringBuffer(videoEndPoint).append("/texttracks/").append(textTrackId).toString(), HttpGet.METHOD_NAME, null, null); }
From source file:com.amos.tool.SelfRedirectStrategy.java
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { return new HttpPost(uri); } else {/*from ww w . j av a 2 s . c om*/ final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGet(uri); } } }
From source file:org.jboss.as.test.integration.security.perimeter.WebConsoleSecurityTestCase.java
@Test public void testGet() throws Exception { getConnection().setRequestMethod(HttpGet.METHOD_NAME); getConnection().connect();//ww w. j av a 2 s .c om assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getConnection().getResponseCode()); }
From source file:ch.cyberduck.core.dropbox.client.AbstractHttpDropboxClient.java
/** * @param method// w w w . j a va2s .c om * @param path * @param params * @param content * @return */ protected HttpUriRequest buildRequest(String method, String path, String[] params, boolean content) { if (method.equals(HttpGet.METHOD_NAME)) { return new HttpGet(this.getUrl(path, params, content)); } else if (method.equals(HttpPost.METHOD_NAME)) { HttpPost post = new HttpPost(this.getUrl(path, params, content)); if (params != null && params.length > 2) { List<BasicNameValuePair> form = new ArrayList<BasicNameValuePair>(); for (int i = 0; i < params.length; i += 2) { if (params[i + 1] != null) { form.add(new BasicNameValuePair("" + params[i], "" + params[i + 1])); } } try { post.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return post; } throw new IllegalArgumentException(method); }
From source file:com.clickntap.vimeo.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpRequestBase request = null;/*from w w w . ja v a2s . c o m*/ String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { out.put(header.getName(), header.getValue()); } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; }
From source file:com.jaspersoft.studio.data.xvia.querydesigner.TrackViaMetadata.java
public void updateMetadata(final DataAdapterDescriptor da, DataAdapterService das, final IProgressMonitor monitor) { if (running)/* w w w . j a v a2 s . c o m*/ return; this.das = das; monitors.add(monitor); running = true; UIUtils.getDisplay().syncExec(new Runnable() { @Override public void run() { if (msg.isDisposed()) return; msg.setText(Messages.DBMetadata_2 + da.getName() + Messages.DBMetadata_3); stackLayout.topControl = mcmp; mcmp.layout(true); composite.layout(true); } }); root.removeChildren(); if (tblMap != null) { tblMap.clear(); } try { RequestService requestService = designer.getRequestService(); GlobalUserResponse gru = requestService.serverRequest(HttpGet.METHOD_NAME, null, "/users", "", new TypeReference<GlobalUserResponse>() { }); SimpleAccountResponse sar = gru.getAccounts().iterator().next(); this.accountId = sar.getId().toString(); List<AppResponse> appresponse = requestService.serverRequest(HttpGet.METHOD_NAME, null, "/accounts/" + sar.getId() + "/apps", "", new TypeReference<List<AppResponse>>() { }); List<TrackViaApp> mcurrent = new ArrayList<TrackViaApp>(); for (AppResponse ar : appresponse) { new TrackViaApp(root, ar.getName(), ar.getId().toString()); } updateUI(root); for (TrackViaApp mcs : mcurrent) { readApp(mcs, monitor, true); } updateItermediateUI(); } catch (Throwable e) { updateUI(root); designer.showError(e); } updateItermediateUI(); UIUtils.getDisplay().asyncExec(new Runnable() { @Override public void run() { // TODO how to refresh tables (or views) ? //Util.refreshTables(root, designer.getRoot(), designer); updateItermediateUI(); } }); monitors.remove(monitor); running = false; }
From source file:org.elasticsearch.client.RequestConverters.java
static Request getMappings(GetMappingsRequest getMappingsRequest) throws IOException { String[] indices = getMappingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.indices(); String[] types = getMappingsRequest.types() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.types(); Request request = new Request(HttpGet.METHOD_NAME, endpoint(indices, "_mapping", types)); Params parameters = new Params(request); parameters.withMasterTimeout(getMappingsRequest.masterNodeTimeout()); parameters.withIndicesOptions(getMappingsRequest.indicesOptions()); parameters.withLocal(getMappingsRequest.local()); return request; }