當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpStatus類代碼示例

本文整理匯總了Java中org.apache.commons.httpclient.HttpStatus的典型用法代碼示例。如果您正苦於以下問題:Java HttpStatus類的具體用法?Java HttpStatus怎麽用?Java HttpStatus使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpStatus類屬於org.apache.commons.httpclient包,在下文中一共展示了HttpStatus類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getUrlContent

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:35,代碼來源:BasicAuthLoader.java

示例2: doPut

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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;
}
 
開發者ID:BriData,項目名稱:DBus,代碼行數:24,代碼來源:HttpRequest.java

示例3: getData

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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 ();
    }
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:20,代碼來源:HdHttpClient.java

示例4: SecureHttpMethodResponse

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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);
        }
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-core,代碼行數:18,代碼來源:HttpClientFactory.java

示例5: isRedirect

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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;
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-core,代碼行數:17,代碼來源:AbstractHttpClient.java

示例6: downloadPacContent

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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");
}
 
開發者ID:convertigo,項目名稱:convertigo-engine,代碼行數:18,代碼來源:PacManager.java

示例7: tryAuthentication

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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!");
       }
}
 
開發者ID:convertigo,項目名稱:convertigo-engine,代碼行數:23,代碼來源:WsReference.java

示例8: send

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
/** {@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();
        }
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:27,代碼來源:HttpSOAPClient.java

示例9: exists

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
/** {@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();
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:19,代碼來源:HttpResource.java

示例10: getResource

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:HttpResource.java

示例11: testAllModulePackages

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
@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());
    }

}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:20,代碼來源:ModulePackagesApiTest.java

示例12: testErrorUrls

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
@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());
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:20,代碼來源:ModulePackagesApiTest.java

示例13: doTestConnection

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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");
    }
}
 
開發者ID:BBVA,項目名稱:mirrorgate-jenkins-builds-collector,代碼行數:17,代碼來源:MirrorGatePublisher.java

示例14: sendBuildExtraData

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
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);
    });
}
 
開發者ID:BBVA,項目名稱:mirrorgate-jenkins-builds-collector,代碼行數:21,代碼來源:MirrorGateListenerHelper.java

示例15: publishBuildData

import org.apache.commons.httpclient.HttpStatus; //導入依賴的package包/類
@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, "");
    }
}
 
開發者ID:BBVA,項目名稱:mirrorgate-jenkins-builds-collector,代碼行數:19,代碼來源:DefaultMirrorGateService.java


注:本文中的org.apache.commons.httpclient.HttpStatus類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。