public List<DataPoint> getData ( final String item, final String type, final Date from, final Date to, final Integer number ) throws Exception { final HttpClient client = new HttpClient (); final HttpMethod method = new GetMethod ( this.baseUrl + "/" + URLEncoder.encode ( item, "UTF-8" ) + "/" + URLEncoder.encode ( type, "UTF-8" ) + "?from=" + URLEncoder.encode ( Utils.isoDateFormat.format ( from ), "UTF-8" ) + "&to=" + URLEncoder.encode ( Utils.isoDateFormat.format ( to ), "UTF-8" ) + "&no=" + number ); client.getParams ().setSoTimeout ( (int)this.timeout ); try { final int status = client.executeMethod ( method ); if ( status != HttpStatus.SC_OK ) { throw new RuntimeException ( "Method failed with error " + status + " " + method.getStatusLine () ); } return Utils.fromJson ( method.getResponseBodyAsString () ); } finally { method.releaseConnection (); } }
/** * Retrieves the content under the given URL with username and passwort * authentication. * * @param url * the URL to read * @param username * @param password * @return the read content. * @throws IOException * if an I/O exception occurs. */ private static byte[] getUrlContent(URL url, String username, String password) throws IOException { final HttpClient client = new HttpClient(); // Set credentials: client.getParams().setAuthenticationPreemptive(true); final Credentials credentials = new UsernamePasswordCredentials( username, password); client.getState() .setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), credentials); // Retrieve content: final GetMethod method = new GetMethod(url.toString()); final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new IOException("Error " + status + " while retrieving " + url); } return method.getResponseBody(); }
public String doPut(String url, String charset, String jsonObj) { String resStr = null; HttpClient htpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url); putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, charset); try { putMethod.setRequestEntity(new StringRequestEntity(jsonObj, "application/json", charset)); int statusCode = htpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + putMethod.getStatusLine()); return null; } byte[] responseBody = putMethod.getResponseBody(); resStr = new String(responseBody, charset); } catch (Exception e) { e.printStackTrace(); } finally { putMethod.releaseConnection(); } return resStr; }
public SecureHttpMethodResponse(HttpMethod method, HostConfiguration hostConfig, EncryptionUtils encryptionUtils) throws AuthenticationException, IOException { super(method); this.hostConfig = hostConfig; this.encryptionUtils = encryptionUtils; if(method.getStatusCode() == HttpStatus.SC_OK) { this.decryptedBody = encryptionUtils.decryptResponseBody(method); // authenticate the response if(!authenticate()) { throw new AuthenticationException(method); } } }
private boolean isRedirect(HttpMethod method) { switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if (method.getFollowRedirects()) { return true; } else { return false; } default: return false; } }
private String downloadPacContent(String url) throws IOException { if (url == null) { Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null"); throw new IOException("Invalid PAC script URL: null"); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("(PacManager) Method failed: " + method.getStatusLine()); } return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8"); }
private static void tryAuthentication(RemoteFileReference wsReference) throws Exception { URL urlToConnect = wsReference.getUrl(); String wsdlUrl = wsReference.getUrlpath(); String username = wsReference.getAuthUser(); String password = wsReference.getAuthPassword(); HttpClient client = new HttpClient(); client.getState().setCredentials( new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()), new UsernamePasswordCredentials(username, password) ); GetMethod get = new GetMethod(wsdlUrl); get.setDoAuthentication( true ); int statuscode = client.executeMethod(get); if (statuscode == HttpStatus.SC_UNAUTHORIZED) { throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!"); } }
/** {@inheritDoc} */ public void send(String endpoint, SOAPMessageContext messageContext) throws SOAPException, SecurityException { PostMethod post = null; try { post = createPostMethod(endpoint, (HttpSOAPRequestParameters) messageContext.getSOAPRequestParameters(), (Envelope) messageContext.getOutboundMessage()); int result = httpClient.executeMethod(post); log.debug("Received HTTP status code of {} when POSTing SOAP message to {}", result, endpoint); if (result == HttpStatus.SC_OK) { processSuccessfulResponse(post, messageContext); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { processFaultResponse(post, messageContext); } else { throw new SOAPClientException("Received " + result + " HTTP response status code from HTTP request to " + endpoint); } } catch (IOException e) { throw new SOAPClientException("Unable to send request to " + endpoint, e); } finally { if (post != null) { post.releaseConnection(); } } }
/** {@inheritDoc} */ public boolean exists() throws ResourceException { HeadMethod headMethod = new HeadMethod(resourceUrl); headMethod.addRequestHeader("Connection", "close"); try { httpClient.executeMethod(headMethod); if (headMethod.getStatusCode() != HttpStatus.SC_OK) { return false; } return true; } catch (IOException e) { throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); } finally { headMethod.releaseConnection(); } }
/** * Gets remote resource. * * @return the remove resource * * @throws ResourceException thrown if the resource could not be fetched */ protected GetMethod getResource() throws ResourceException { GetMethod getMethod = new GetMethod(resourceUrl); getMethod.addRequestHeader("Connection", "close"); try { httpClient.executeMethod(getMethod); if (getMethod.getStatusCode() != HttpStatus.SC_OK) { throw new ResourceException("Unable to retrieve resource URL " + resourceUrl + ", received HTTP status code " + getMethod.getStatusCode()); } return getMethod; } catch (IOException e) { throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); } }
@Test public void testAllModulePackages() throws Exception { setRequestContext(nonAdminUserName); HttpResponse response = getAll(MODULEPACKAGES, null, HttpStatus.SC_OK); assertNotNull(response); PublicApiClient.ExpectedPaging paging = parsePaging(response.getJsonResponse()); assertNotNull(paging); if (paging.getCount() > 0) { List<ModulePackage> modules = parseRestApiEntries(response.getJsonResponse(), ModulePackage.class); assertNotNull(modules); assertEquals(paging.getCount().intValue(), modules.size()); } }
@Test public void testErrorUrls() throws Exception { setRequestContext(null); Map<String, String> params = createParams(null, null); //Call an endpoint that doesn't exist HttpResponse response = publicApiClient.get(getScope(), MODULEPACKAGES+"/fred/blogs/king/kong/got/if/wrong", null, null, null, params); assertNotNull(response); assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); assertEquals("no-cache", response.getHeaders().get("Cache-Control")); assertEquals("application/json;charset=UTF-8", response.getHeaders().get("Content-Type")); PublicApiClient.ExpectedErrorResponse errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse()); assertNotNull(errorResponse); assertNotNull(errorResponse.getErrorKey()); assertNotNull(errorResponse.getBriefSummary()); }
public FormValidation doTestConnection( @QueryParameter("mirrorGateAPIUrl") final String mirrorGateAPIUrl, @QueryParameter("mirrorgateCredentialsId") final String credentialsId) throws Descriptor.FormException { MirrorGateService testMirrorGateService = getMirrorGateService(); if (testMirrorGateService != null) { MirrorGateResponse response = testMirrorGateService.testConnection(); return response.getResponseCode() == HttpStatus.SC_OK ? FormValidation.ok("Success") : FormValidation.error("Failure<" + response.getResponseCode() + ">"); } else { return FormValidation.error("Failure"); } }
private void sendBuildExtraData(BuildBuilder builder, TaskListener listener) { List<String> extraUrl = MirrorGateUtils.getURLList(); extraUrl.forEach(u -> { MirrorGateResponse response = getMirrorGateService() .sendBuildDataToExtraEndpoints(builder.getBuildData(), u); String msg = "POST to " + u + " succeeded!"; Level level = Level.FINE; if (response.getResponseCode() != HttpStatus.SC_CREATED) { msg = "POST to " + u + " failed with code: " + response.getResponseCode(); level = Level.WARNING; } if (listener != null && level == Level.FINE) { listener.getLogger().println(msg); } LOG.log(level, msg); }); }
@Override public MirrorGateResponse publishBuildData(BuildDTO request) { try { MirrorGateResponse callResponse = buildRestCall().makeRestCallPost( MirrorGateUtils.getMirrorGateAPIUrl() + "/api/builds", MirrorGateUtils.convertObjectToJson(request), MirrorGateUtils.getMirrorGateUser(), MirrorGateUtils.getMirrorGatePassword()); if (callResponse.getResponseCode() != HttpStatus.SC_CREATED) { LOG.log(Level.SEVERE, "MirrorGate: Build Publisher post may have failed. Response: {0}", callResponse.getResponseCode()); } return callResponse; } catch (IOException e) { LOG.log(Level.SEVERE, "MirrorGate: Error posting to mirrorGate", e); return new MirrorGateResponse(HttpStatus.SC_CONFLICT, ""); } }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost <file>"); System.out.println("<file> - full path to a file to be posted"); System.exit(1); } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity( new FileInputStream(file), file.length())); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } }
public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { HttpVersion ver = request.getRequestLine().getHttpVersion(); if (ver.equals(HttpVersion.HTTP_1_0)) { return false; } else { SimpleResponse response = new SimpleResponse(); response.setStatusLine(ver, HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); response.addHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); // Make sure the request body is fully consumed request.getBodyBytes(); conn.writeResponse(response); return true; } }
/** * Tests ability to use HTTP/1.0 to execute CONNECT method and HTTP/1.1 to * execute methods once the tunnel is established. */ public void testTunnellingParamsHostHTTP10AndMethodHTTP11() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); GetMethod httpget = new GetMethod("/test/"); httpget.getParams().setVersion(HttpVersion.HTTP_1_1); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); assertEquals(HttpVersion.HTTP_1_1, httpget.getEffectiveVersion()); } finally { httpget.releaseConnection(); } }
public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { String uri = request.getRequestLine().getUri(); HttpVersion httpversion = request.getRequestLine().getHttpVersion(); if ("/miss/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/hit/")); response.setBodyString("Missed!"); } else if ("/hit/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_OK); response.setBodyString("Hit!"); } else { response.setStatusLine(httpversion, HttpStatus.SC_NOT_FOUND); response.setBodyString(uri + " not found"); } return true; }
public void testDefaults() throws IOException { this.server.setHttpService(new SimpleService()); this.client.getParams().setParameter(HttpMethodParams.USER_AGENT, "test"); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/miss/"); try { this.client.executeMethod(hostconfig, httpget); } finally { httpget.releaseConnection(); } assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("test", httpget.getRequestHeader("User-Agent").getValue()); assertEquals("test", httpget.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", hostconfig.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", client.getParams(). getParameter(HttpMethodParams.USER_AGENT)); }
public void testBasicAuthenticationWithNoCreds() throws IOException { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } finally { httpget.releaseConnection(); } }
public void testCustomAuthorizationHeader() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); String authResponse = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); httpget.addRequestHeader(new Header("Authorization", authResponse)); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); }
/** * Make sure preemptive authorization works when the server requires NLM. * @throws Exception */ public void testPreemptiveAuthorization() throws Exception { NTCredentials creds = new NTCredentials("testuser", "testpass", "host", "domain"); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, creds); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new PreemptiveNTLMAuthService()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); }
private SimpleResponse performBasicHandshake( final SimpleHttpServerConnection conn, final SimpleRequest request) { SimpleResponse response = new SimpleResponse(); response.setStatusLine( request.getRequestLine().getHttpVersion(), HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) { response.setBodyString("unauthorized"); } response.addHeader(new Header("Proxy-Authenticate", "basic realm=\"" + this.realm + "\"")); if (this.keepalive) { response.addHeader(new Header("Proxy-Connection", "keep-alive")); conn.setKeepAlive(true); } else { response.addHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); } return response; }
public static SimpleResponse getResponse(int statusCode) { Integer code = new Integer(statusCode); SimpleResponse response = (SimpleResponse)responses.get(code); if (response == null) { response = new SimpleResponse(); response.setStatusLine(HttpVersion.HTTP_1_0, statusCode); response.setHeader(new Header("Content-Type", "text/plain; charset=US-ASCII")); String s = HttpStatus.getStatusText(statusCode); if (s == null) { s = "Error " + statusCode; } response.setBodyString(s); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Content-Lenght", Integer.toString(s.length()))); responses.put(code, response); } return response; }
private SimpleResponse performBasicHandshake( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { SimpleResponse response = new SimpleResponse(); response.setStatusLine( request.getRequestLine().getHttpVersion(), HttpStatus.SC_UNAUTHORIZED); if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) { response.setBodyString("unauthorized"); } response.addHeader(new Header("WWW-Authenticate", "basic realm=\"" + this.realm + "\"")); if (this.keepalive) { response.addHeader(new Header("Connection", "keep-alive")); conn.setKeepAlive(true); } else { response.addHeader(new Header("Connection", "close")); conn.setKeepAlive(false); } return response; }
@Override public File downloadToFile(String key) throws Exception { String ip = ips[rand.nextInt(ips.length)]; String url = String.format(urlPattern, ip, key); LOG.debug("Download url:" + url); try { GetMethod get = new GetMethod(url); int code = client.executeMethod(get); if (code != HttpStatus.SC_OK) { throw new IOException("Failed to download file from url " + url); } File file = SourceUtil.getRandomFile(); OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(get.getResponseBodyAsStream(), outputStream); outputStream.flush(); outputStream.close(); return file; } catch (Exception e) { throw new IOException("Failed to download file from url " + url, e); } }
private String iniciarTramite(String xmlData, String xmlConfig) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(urlTramitacio); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); method.getParams().setContentCharset("UTF-8"); method.addParameter("xmlData", xmlData); method.addParameter("xmlConfig", xmlConfig); try { int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { log("Error iniciando tramite: " + status); return null; } return method.getResponseBodyAsString(); } catch (IOException e) { return null; } finally { method.releaseConnection(); } }
private List<Task> processRSS(@NotNull GetMethod method) throws Exception { // Basic authorization should be enough int code = myRepository.getHttpClient().executeMethod(method); if (code != HttpStatus.SC_OK) { throw new Exception(TaskBundle.message("failure.http.error", code, method.getStatusText())); } Element root = new SAXBuilder(false).build(method.getResponseBodyAsStream()).getRootElement(); Element channel = root.getChild("channel"); if (channel != null) { List<Element> children = channel.getChildren("item"); LOG.debug("Total issues in JIRA RSS feed: " + children.size()); return ContainerUtil.map(children, new Function<Element, Task>() { public Task fun(Element element) { return new JiraSoapTask(element, myRepository); } }); } else { LOG.warn("JIRA channel not found"); } return ContainerUtil.emptyList(); }
private void deleteFax( DefaultHttpClient client, FaxConfig faxConfig, FaxJob fax ) throws ClientProtocolException, IOException { HttpDelete mDelete = new HttpDelete(faxConfig.getUrl() + PATH + "/" + URLEncoder.encode(faxConfig.getFaxUser(),"UTF-8") + "/" + URLEncoder.encode(fax.getFile_name(),"UTF-8") ); mDelete.setHeader("accept", "application/json"); mDelete.setHeader("user", faxConfig.getFaxUser()); mDelete.setHeader("passwd", faxConfig.getFaxPasswd()); log.info("Deleting Fax file " + fax.getFile_name() + " from the host server."); HttpResponse response = client.execute(mDelete); mDelete.reset(); if( !(response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) ) { log.debug("Failed to delete Fax file " + fax.getFile_name() + " from the host server."); throw new ClientProtocolException("CANNOT DELETE " + fax.getFile_name()); } else { log.info("Fax file " + fax.getFile_name() + " has been deleted from the host server."); } }
public void get() throws UnsupportedEncodingException { HttpClient client = new HttpClient(); String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0"; String INFO =new URLCodec().encode("who are you","utf-8"); String requesturl = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO; GetMethod getMethod = new GetMethod(requesturl); try { int stat = client.executeMethod(getMethod); if (stat != HttpStatus.SC_OK) log.error("get失败!"); byte[] responseBody = getMethod.getResponseBody(); String content=new String(responseBody ,"utf-8"); log.info(content); }catch (Exception e){ log.error(""+e.getLocalizedMessage()); }finally { getMethod.releaseConnection(); } }
@Override public GeoLocation getCurrentGeoLocation() throws Exception { HttpClient httpClient = component.getHttpClient(); GetMethod getMethod = new GetMethod("http://freegeoip.io/json/"); try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new IllegalStateException("Got the unexpected http-status '" + getMethod.getStatusLine() + "' for the geolocation"); } String geoLocation = component.getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, getMethod.getResponseBodyAsStream()); if (isEmpty(geoLocation)) { throw new IllegalStateException("Got the unexpected value '" + geoLocation + "' for the geolocation"); } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(geoLocation, JsonNode.class); JsonNode latitudeNode = notNull(node.get("latitude"), "latitude"); JsonNode longitudeNode = notNull(node.get("longitude"), "longitude"); return new GeoLocation(longitudeNode.asText(), latitudeNode.asText()); } finally { getMethod.releaseConnection(); } }
public static void query(String bookid) { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("action", "query"); post.addParameter("bookid", bookid); try{ int status = client.executeMethod(post); if (status == HttpStatus.SC_OK){ String response = post.getResponseBodyAsString(); System.out.println(response); }else{ System.out.println(status); } }catch(Exception ex){ ex.printStackTrace(); } }
public static void save(String record) { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("action", "save"); post.addParameter("record", record); try{ int status = client.executeMethod(post); if (status == HttpStatus.SC_OK){ String response = post.getResponseBodyAsString(); System.out.println(response); }else{ System.out.println(status); } }catch(Exception ex){ ex.printStackTrace(); } }
public static void coder() { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("action", "coder"); try{ int status = client.executeMethod(post); if (status == HttpStatus.SC_OK){ String response = post.getResponseBodyAsString(); System.out.println(response); }else{ System.out.println(status); } }catch(Exception ex){ ex.printStackTrace(); } }
public static boolean deleteAllForRecord(String url, int rn) { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("operation", "deleteAllForRecord"); post.addParameter("rn", String.valueOf(rn)); try{ int status = client.executeMethod(post); if (status == HttpStatus.SC_OK){ log.info("Files for record rn=" + rn + " successfully deleted."); return true; }else{ log.fatal("Delete files for record rn=" + rn + " failed: " + HttpStatus.getStatusText(status)); return false; } }catch(Exception ex){ log.fatal(ex); return false; } }
public static boolean delete(String url, int id) { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter("operation", "delete"); post.addParameter("id", String.valueOf(id)); try{ int status = client.executeMethod(post); if (status == HttpStatus.SC_OK){ log.info("File with id=" + id + " successfully deleted."); return true; }else{ log.fatal("Delete file id=" + id + " failed: " + HttpStatus.getStatusText(status)); return false; } }catch(Exception ex){ log.fatal(ex); return false; } }
@Test public void request_pdb_unauthorized() throws Exception { myFixture.getLoginConfiguration().setGuestLoginAllowed(false); final File artDirectory = createTempDir(); assertTrue(new File(artDirectory, "foo").createNewFile());; myBuildType.setArtifactPaths(artDirectory.getAbsolutePath()); RunningBuildEx build = startBuild(); finishBuild(build, false); final String fileSignature = "8EF4E863187C45E78F4632152CC82FEB"; final String fileName = "secur32.pdb"; final String filePath = "foo/secur32.pdb"; myRequest.setRequestURI("mock", getRegisterPdbUrl(fileSignature, fileName, filePath)); doGet(); assertEquals(HttpStatus.SC_UNAUTHORIZED, myResponse.getStatus()); }
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) { try { final Pair<String, Integer> hostAndPort = validateUrl(url); final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager()); if ((user != null) && (password != null)) { httpclient.getParams().setAuthenticationPreemptive(true); final Credentials defaultcreds = new UsernamePasswordCredentials(user, password); httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); } // Execute the method. final GetMethod method = new GetMethod(url); final int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { s_logger.error("Failed to read from URL: " + url); return null; } return method.getResponseBodyAsStream(); } catch (final Exception ex) { s_logger.error("Failed to read from URL: " + url); return null; } }
@Test public void postMethod() throws IOException, InterruptedException { Transaction transaction = source.channel.getTransaction(); transaction.begin(); for (String testRequest : testRequests) { final PostMethod post = executePost("/write", ( testRequest ).getBytes()); Assert.assertEquals(testRequest, post.getStatusCode(), HttpStatus.SC_OK); } transaction.commit(); transaction.close(); Thread.sleep(500); final Transaction tx2 = source.channel.getTransaction(); tx2.begin(); final BatchEvent take = (BatchEvent) source.channel.take(); Assert.assertNotNull(take); Assert.assertEquals( new String(take.iterator().next()), "put l.numeric.TESTHOST/nobus/test 1364451167 3.14 legacy=true"); tx2.commit(); tx2.close(); }