Java 类org.apache.commons.httpclient.HttpMethodBase 实例源码

项目:fax4j    文件:ApacheHTTPClientTest.java   
/**
 * Test 
 * 
 * @throws  Exception
 *          Any exception
 */
@Test
public void createMultiPartRequestContentWithDataTest() throws Exception
{
    String string="FILE_DATA";
    File file=File.createTempFile("temp_",".txt");
    file.deleteOnExit();
    byte[] input=string.getBytes(IOHelper.getDefaultEncoding());
    IOHelper.writeFile(input,file);

    HTTPRequest httpRequest=new HTTPRequest();
    ContentPart<?>[] parts=new ContentPart[5];  //make array bigger to simulate null parts
    parts[0]=new ContentPart<String>("string_part","TEST_DATA",ContentPartType.STRING);
    parts[1]=new ContentPart<String>("string_part2","TEST_DATA2",ContentPartType.STRING);
    parts[2]=new ContentPart<File>("file_part",file,ContentPartType.FILE);
    httpRequest.setContent(parts);
    HttpMethodBase method=this.client.createMethod("http://fax4j.org",HTTPMethod.POST);
    RequestEntity output=this.client.createMultiPartRequestContent(httpRequest,method);

    file.delete();

    Assert.assertNotNull(output);
    Assert.assertEquals(MultipartRequestEntity.class,output.getClass());
}
项目:fax4j    文件:ApacheHTTPClient.java   
/**
 * This function sets the header properties in the HTTP method.
 * 
 * @param   httpRequest
 *          The HTTP request
 * @param   httpMethodClient
 *          The apache HTTP method
 */
protected void setupHTTPRequestHeaderProperties(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
{
    //setup header properties
    Properties headerProperties=httpRequest.getHeaderProperties();
    if(headerProperties!=null)
    {
        Iterator<Entry<Object,Object>> iterator=headerProperties.entrySet().iterator();
        Entry<Object,Object> entry=null;
        while(iterator.hasNext())
        {
            //get next entry
            entry=iterator.next();

            //set header values
            httpMethodClient.addRequestHeader((String)entry.getKey(),(String)entry.getValue());
        }
    }
}
项目:fax4j    文件:ApacheHTTPClientTest.java   
/**
 * Test 
 * 
 * @throws  Exception
 *          Any exception
 */
@Test
public void setupHTTPRequestHeaderPropertiesWithDataTest() throws Exception
{
    Properties headerProperties=new Properties();
    headerProperties.setProperty("key1","value1");
    headerProperties.setProperty("key2","value2");
    headerProperties.setProperty("key3","value3");
    HTTPRequest httpRequest=new HTTPRequest();
    httpRequest.setHeaderProperties(headerProperties);
    HttpMethodBase method=this.client.createMethod("http://fax4j.org",HTTPMethod.GET);
    this.client.setupHTTPRequestHeaderProperties(httpRequest,method);
    Header[] headers=method.getRequestHeaders();
    Assert.assertEquals(3,headers.length);
    Assert.assertEquals("value1",method.getRequestHeader("key1").getValue());
    Assert.assertEquals("value2",method.getRequestHeader("key2").getValue());
    Assert.assertEquals("value3",method.getRequestHeader("key3").getValue());
}
项目:detcrc-portal    文件:NVCLDataServiceMethodMaker.java   
/**
 * When triggered, the wfs download service will call the Observations and Measurements WFS request,
 * get the GeoSciML? output and compress it into a zip file for download. The user will have to
 * first make a download request and come back to check the download status. When the download is
 * completed, a link will be provided to download the requested Observations and Measurements output
 * in zip format.
 *
 * This method will return a HTML stream
 *
 * @param serviceUrl The URL of the NVCLDataService
 * @param email The user's email address
 * @param boreholeId selected borehole id (use as feature id for filtering purpose)
 * @param omUrl The valid url for the Observations and Measurements WFS
 * @param typeName The url parameter for the wfs request
 * @return
 */
public HttpMethodBase getDownloadWFSMethod(String serviceUrl, String email, String boreholeId, String omUrl, String typeName) {
    GetMethod method = new GetMethod(urlPathConcat(serviceUrl, "downloadwfs.html"));

    ArrayList<NameValuePair> valuePairs = new ArrayList<NameValuePair>();

    //set all of the parameters
    valuePairs.add(new NameValuePair("email", email));
    valuePairs.add(new NameValuePair("boreholeid", boreholeId));
    valuePairs.add(new NameValuePair("serviceurl", omUrl));
    valuePairs.add(new NameValuePair("typename", typeName));

    //attach them to the method
    method.setQueryString((NameValuePair[]) valuePairs.toArray(new NameValuePair[valuePairs.size()]));

    return method;
}
项目:detcrc-portal    文件:BoreholeService.java   
/**
 * Get all boreholes from a given service url and return the response
 * @param serviceURL
 * @param bbox Set to the bounding box in which to fetch results, otherwise set it to null
 * @param restrictToIDList [Optional] A list of gml:id values that the resulting filter should restrict its search space to
 * @return
 * @throws Exception
 */
public WFSTransformedResponse getAllBoreholes(String serviceURL, String boreholeName, String custodian, String dateOfDrilling, int maxFeatures, FilterBoundingBox bbox, List<String> restrictToIDList) throws Exception {
    String filterString;
    BoreholeFilter nvclFilter = new BoreholeFilter(boreholeName, custodian, dateOfDrilling, restrictToIDList);
    if (bbox == null) {
        filterString = nvclFilter.getFilterStringAllRecords();
    } else {
        filterString = nvclFilter.getFilterStringBoundingBox(bbox);
    }



    HttpMethodBase method = null;
    try {
        // Create a GetFeature request with an empty filter - get all
        method = this.generateWFSRequest(serviceURL, "gsml:Borehole", null, filterString, maxFeatures, null, ResultType.Results);
        String responseGml = this.httpServiceCaller.getMethodResponseAsString(method);
        String responseKml = this.wfsToKml.convert(responseGml, serviceURL);


        return new WFSTransformedResponse(responseGml, responseKml, method);
    } catch (Exception ex) {
        throw new PortalServiceException(method, ex);
    }
}
项目:detcrc-portal    文件:TestEarthResourcesFilterController.java   
/**
 * Test doing a mine filter and getting all mines
 * @throws Exception
 */
@Test
public void testDoMineFilterAllMines() throws Exception {
    final String serviceURL = "http://localhost?";
    final String mineName = ""; //to get all mines
    final HttpMethodBase mockMethod = context.mock(HttpMethodBase.class);
    final String expectedKML = "<kml/>";
    final String expectedGML = "<gml/>";

    context.checking(new Expectations() {{
        allowing(mockMethod).getURI();will(returnValue(new URI(serviceURL, true)));
        oneOf(mineralOccurrenceService).getMinesGml(serviceURL, mineName, null, 0);will(returnValue(new WFSTransformedResponse(expectedGML, expectedKML, mockMethod)));
    }});

    //call with updateCSWRecords dud url
    ModelAndView modelAndView = this.earthResourcesFilterController.doMineFilter(serviceURL, mineName, null, 0);

    //Ensure that we get a valid response
    testMAVResponse(modelAndView, new Boolean(true), expectedGML, expectedKML);
}
项目:detcrc-portal    文件:NvclVocabService.java   
/**
 * Gets all RDF concepts at the specified repository as a single JENA Model. The results
 * will be requested page by page until the entire repository has been traversed.
 *
 * @return
 * @throws PortalServiceException
 */
public Model getAllScalarConcepts() throws PortalServiceException {
    Model model = ModelFactory.createDefaultModel();
    int pageNumber = 0;
    int pageSize = this.getPageSize();

    //Request each page in turn - put the results into Model
    do {
        HttpMethodBase method = ((NvclVocabMethodMaker)sissVocMethodMaker).getAllScalars(getBaseUrl(), getRepository(), Format.Rdf, pageSize, pageNumber);
        if (requestPageOfConcepts(method, model)) {
            pageNumber++;
        } else {
            break;
        }
    } while (true);

    return model;
}
项目:detcrc-portal    文件:TestNVCLController.java   
/**
 * Tests that hylogger filter uses the correct functions when the underlying hylogger lookup returns no results.
 *
 * @throws Exception the exception
 */
@Test
public void testHyloggerFilterNoDatasets() throws Exception {
    final String serviceUrl = "http://fake.com/wfs";
    final String nameFilter = "filterBob";
    final String custodianFilter = "filterCustodian";
    final String filterDate = "1986-10-09";
    final int maxFeatures = 10;
    final FilterBoundingBox bbox = new FilterBoundingBox("EPSG:4326", new double[] {1., 2.}, new double[] {3., 4.});
    final boolean onlyHylogger = true;
    final HttpMethodBase mockHttpMethodBase = context.mock(HttpMethodBase.class);
    final URI httpMethodURI = new URI("http://example.com", true);

    context.checking(new Expectations() {{
        oneOf(mockBoreholeService).discoverHyloggerBoreholeIDs(with(equal(mockCSWService)),with(any(CSWRecordsFilterVisitor.class)));
        will(returnValue(new ArrayList<String>()));

        allowing(mockHttpMethodBase).getURI();
        will(returnValue(httpMethodURI));
    }});

    ModelAndView response = this.nvclController.doBoreholeFilter(serviceUrl, nameFilter, custodianFilter, filterDate, maxFeatures, bbox, onlyHylogger);
    Assert.assertFalse((Boolean) response.getModel().get("success"));
}
项目:detcrc-portal    文件:MineralOccurrenceDownloadService.java   
/**
 * Given a list of parameters, call a service and get the Mineral Activity features as GML/KML
 * @param serviceURL
 * @param mineName
 * @param startDate
 * @param endDate
 * @param oreProcessed
 * @param producedMaterial
 * @param cutOffGrade
 * @param production
 * @param maxFeatures
 * @param bbox [Optional] the spatial bounds to constrain the result set
 * @return
 * @throws Exception
 */
public InputStream downloadMiningActivityGml(String serviceURL,
                                    String mineName,
                                    String startDate,
                                    String endDate,
                                    String oreProcessed,
                                    String producedMaterial,
                                    String cutOffGrade,
                                    String production,
                                    int maxFeatures,
                                    FilterBoundingBox bbox
                                    ) throws Exception {

    //create the filter
    MiningActivityFilter filter = new MiningActivityFilter(mineName, startDate, endDate, oreProcessed, producedMaterial, cutOffGrade, production);
    String filterString = generateFilterString(filter, bbox);

    HttpMethodBase method = generateWFSRequest(serviceURL, MINING_ACTIVITY_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Results);
    try {
        return httpServiceCaller.getMethodResponseAsStream(method,client);
    } catch (Exception ex) {
        throw new PortalServiceException(method, ex);
    }
}
项目:detcrc-portal    文件:MineralOccurrenceService.java   
/**
 * Gets the GML/KML response for all mines matching the specified parameters
 * @param serviceUrl a Web Feature Service URL
 * @param mineName [Optional] The mine name to constrain the result set
 * @param bbox [Optional] the spatial bounds to constrain the result set
 * @param maxFeatures The maximum number of features to request
 * @return
 * @throws PortalServiceException
 */
public WFSTransformedResponse getMinesGml(String serviceUrl, String mineName, FilterBoundingBox bbox, int maxFeatures) throws PortalServiceException {
    MineFilter filter = new MineFilter(mineName);
    String filterString = generateFilterString(filter, bbox);

    HttpMethodBase method = null;
    try {
        method = generateWFSRequest(serviceUrl, MINE_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Results);
        String responseGml = httpServiceCaller.getMethodResponseAsString(method);
        String responseKml = gmlToKml.convert(responseGml, serviceUrl);

        return new WFSTransformedResponse(responseGml, responseKml, method);
    } catch (Exception ex) {
        throw new PortalServiceException(method, "Error when attempting to download Mines GML", ex);
    }
}
项目:detcrc-portal    文件:TestEarthResourcesFilterController.java   
/**
 * Test doing a mine filter and getting all mines
 * @throws Exception
 */
@Test
public void testDoMineFilterSingleMine() throws Exception {
    final String serviceURL = "http://localhost?";
    final String mineName = "mineName"; //to get all mines
    final HttpMethodBase mockMethod = context.mock(HttpMethodBase.class);
    final String expectedKML = "<kml/>";
    final String expectedGML = "<gml/>";

    context.checking(new Expectations() {{
        allowing(mockMethod).getURI();will(returnValue(new URI(serviceURL, true)));
        oneOf(mineralOccurrenceService).getMinesGml(serviceURL, mineName, null, 0);will(returnValue(new WFSTransformedResponse(expectedGML, expectedKML, mockMethod)));
    }});

    //call with updateCSWRecords dud url
    ModelAndView modelAndView = this.earthResourcesFilterController.doMineFilter(serviceURL, mineName, null, 0);

    //Ensure that we get a valid response
    testMAVResponse(modelAndView, new Boolean(true), expectedGML, expectedKML);
}
项目:detcrc-portal    文件:MineralOccurrenceService.java   
/**
 * Given a list of parameters, call a service and get the count of Mineral Occurrence GML
 * @param serviceURL
 * @param commodityName
 * @param measureType
 * @param minOreAmount
 * @param minOreAmountUOM
 * @param minCommodityAmount
 * @param minCommodityAmountUOM
 * @param cutOffGrade
 * @param cutOffGradeUOM
 * @param bbox [Optional] the spatial bounds to constrain the result set
 * @return
 */
public WFSCountResponse getMineralOccurrenceCount(String serviceURL,
                                       String commodityName,
                                       String measureType,
                                       String minOreAmount,
                                       String minOreAmountUOM,
                                       String minCommodityAmount,
                                       String minCommodityAmountUOM,
                                       int maxFeatures,
                                       FilterBoundingBox bbox) throws PortalServiceException {

    MineralOccurrenceFilter filter = new MineralOccurrenceFilter(commodityName,
                                       measureType,
                                       minOreAmount,
                                       minOreAmountUOM,
                                       minCommodityAmount,
                                       minCommodityAmountUOM);

    String filterString = generateFilterString(filter, bbox);
    HttpMethodBase method = generateWFSRequest(serviceURL, MINERAL_OCCURRENCE_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Hits);
    return getWfsFeatureCount(method);
}
项目:detcrc-portal    文件:MineralOccurrenceService.java   
/**
 * Given a list of parameters, call a service and get the count of Mineral Activity features
 * @param serviceURL
 * @param mineName
 * @param startDate
 * @param endDate
 * @param oreProcessed
 * @param producedMaterial
 * @param cutOffGrade
 * @param production
 * @param maxFeatures
 * @param bbox [Optional] the spatial bounds to constrain the result set
 * @return
 * @throws Exception
 */
public WFSCountResponse getMiningActivityCount(String serviceURL,
                                    String mineName,
                                    String startDate,
                                    String endDate,
                                    String oreProcessed,
                                    String producedMaterial,
                                    String cutOffGrade,
                                    String production,
                                    int maxFeatures,
                                    FilterBoundingBox bbox
                                    ) throws Exception {

    //create the filter
    MiningActivityFilter filter = new MiningActivityFilter(mineName, startDate, endDate, oreProcessed, producedMaterial, cutOffGrade, production);
    String filterString = generateFilterString(filter, bbox);

    HttpMethodBase method = generateWFSRequest(serviceURL, MINING_ACTIVITY_FEATURE_TYPE, null, filterString, maxFeatures, null, ResultType.Hits);
    return getWfsFeatureCount(method);
}
项目:detcrc-portal    文件:ErmlVocabService.java   
/**
 * Gets all RDF concepts at the specified repository as a single JENA Model. The results
 * will be requested page by page until the entire repository has been traversed.
 *
 * @return
 * @throws PortalServiceException
 */
public Model getAllCommodityConcepts() throws PortalServiceException {
    Model model = ModelFactory.createDefaultModel();
    int pageNumber = 0;
    int pageSize = this.getPageSize();

    //Request each page in turn - put the results into Model
    do {
        HttpMethodBase method = ((CommodityVocabMethodMaker)sissVocMethodMaker).getAllCommodities(getBaseUrl(), getRepository(), Format.Rdf, pageSize, pageNumber);
        if (requestPageOfConcepts(method, model)) {
            pageNumber++;
        } else {
            break;
        }
    } while (true);

    return model;
}
项目:detcrc-portal    文件:PressureDBExceptionParser.java   
/**
 * Will attempt to parse an <DataServiceError> element
 *
 * Will throw an PressureDBException if document does contain an <DataServiceError>, otherwise it will do nothing
 * @param doc
 * @throws PressureDBException
 */
public static void checkForExceptionResponse(Document doc) throws PortalServiceException {
    XPath xPath = XPathFactory.newInstance().newXPath();

    try {
        //Check for an exception response
        NodeList exceptionNodes = (NodeList)xPath.evaluate("/DataServiceError", doc, XPathConstants.NODESET);
        if (exceptionNodes.getLength() > 0) {
            Node exceptionNode = exceptionNodes.item(0);

            throw new PortalServiceException((HttpMethodBase)null, exceptionNode.getTextContent());
        }
    } catch (XPathExpressionException ex) {
        //This should *hopefully* never occur
        log.error("Error whilst attempting to check for errors", ex);
    }
}
项目:alfresco-repository    文件:RemoteConnectorRequestImpl.java   
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
    if ("GET".equals(method))
    {
        return new GetMethod(url);
    }
    if ("POST".equals(method))
    {
        return new PostMethod(url);
    }
    if ("PUT".equals(method))
    {
        return new PutMethod(url);
    }
    if ("DELETE".equals(method))
    {
        return new DeleteMethod(url);
    }
    if (TestingMethod.METHOD_NAME.equals(method))
    {
        return new TestingMethod(url);
    }
    throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
项目:alfresco-repository    文件:RemoteConnectorRequestImpl.java   
protected static HttpMethodBase buildHttpClientMethod(String url, Class<? extends HttpMethodBase> method)
{
    HttpMethodBase request = null;
    try
    {
        request = method.getConstructor(String.class).newInstance(url);
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("HttpClient broken", e);
    }
    return request;
}
项目:oscm    文件:ProxyFilter.java   
/**
 * Will create the method and execute it. After this the method is sent to a
 * ResponseHandler that is returned.
 * 
 * @param httpRequest
 *            Request we are receiving from the client
 * @param url
 *            The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException
 *             If the method specified by the request isn't handled
 * @throws IOException
 *             When there is a problem with the streams
 * @throws HttpException
 *             The httpclient can throw HttpExcetion when executing the
 *             method
 */
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory
            .createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException(
                    "Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}
项目:hadoop    文件:SwiftRestClient.java   
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
项目:sling-org-apache-sling-launchpad-integration-tests    文件:SLING2082Test.java   
private void runTest(HttpMethodBase m, int expectedStatus) throws Exception {
    m.setFollowRedirects(false);
    final int status = httpClient.executeMethod(m);
    assertEquals(expectedStatus, status);
    final String content = getResponseBodyAsStream(m, 0);
    final String scriptTag = "<script>";
    assertFalse("Content should not contain '" + scriptTag + "'", content.contains(scriptTag));
}
项目:alfresco-remote-api    文件:LocalWebScriptConnectorServiceImpl.java   
/**
 * Builds a new Request object, using HttpClient method descriptions
 */
public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method)
{
    // Get the method name
    String methodName;
    try
    {
        HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url);
        methodName = httpMethod.getName();
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("Error identifying method name", e);
    }

    // Build and return
    return buildRequest(url, methodName);
}
项目:alfresco-remote-api    文件:HttpResponse.java   
public String getResponse()
{
    if (responseBytes != null)
    {
        if (method instanceof HttpMethodBase)
        {
            // mimic method.getResponseBodyAsString
            return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
        }
        else
        {
            return new String(responseBytes);
        }
    }
    else
    {
        return null;
    }
}
项目:lib-commons-httpclient    文件:HttpMethodCloner.java   
private static void copyHttpMethodBase(
  HttpMethodBase m, HttpMethodBase copy) {
    try {
        copy.setParams((HttpMethodParams)m.getParams().clone());
    } catch (CloneNotSupportedException e) {
        // Should never happen
    }
}
项目:aliyun-oss-hadoop-fs    文件:SwiftRestClient.java   
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
项目:scribe    文件:ZDCRMTest.java   
@SuppressWarnings("unused")
private final void showHeaders(final HttpMethodBase methodBase) {

  final Header[] headers = methodBase.getResponseHeaders();

  for (int i = 0; i < headers.length; i++) {
    System.out.println("header name: " + headers[i].getName());
    System.out.println("header value: " + headers[i].getValue());
  }
}
项目:javabase    文件:OldHttpClientApi.java   
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception {
    InputStream in = null;
    try {
        method.addRequestHeader("Connection", "close");
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
        //设置连接时候一些参数
        params.setConnectionTimeout(timeout);
        params.setSoTimeout(timeout);
        params.setStaleCheckingEnabled(false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);

        int stat =  client.executeMethod(method);
        if (stat != HttpStatus.SC_OK)
            log.error("get失败!");

        //method.getResponseBody()
        in = method.getResponseBodyAsStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        return baos.toByteArray();
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
}
项目:big-c    文件:SwiftRestClient.java   
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
项目:javacode-demo    文件:HttpReq.java   
/**
 * 执行HTTP GET/POST
 * @return 执行结果
 * @throws IOException
 */
public HttpResponse execute() throws IOException {
    HttpClient httpClient = createHttpClient();
    HttpMethodBase method = null;

    try {
        createProxy(httpClient);
        basicAuth(httpClient);

        method = createMethod(); // 放在try中,防止url有错误,异常抛出

        return executeMethod(httpClient, method);
    } finally {
        shutdown(method);
    }
}
项目:javacode-demo    文件:HttpReq.java   
private void shutdown(HttpMethodBase method) {
    if (method != null) {
        method.releaseConnection();
    }
    if (!externalConnectionManager) {
        ((SimpleHttpConnectionManager) httpConnectionManager).shutdown();
    }
}
项目:javacode-demo    文件:HttpReq.java   
private HttpResponse executeMethod(HttpClient httpClient, HttpMethodBase method) throws IOException {
    int responseCode = httpClient.executeMethod(method);
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setResponseCode(responseCode);
    httpResponse.setResponseContent(method.getResponseBodyAsStream());
    httpResponse.setResponseCharSet(method.getResponseCharSet());
    return httpResponse;
}
项目:http4e    文件:HttpMethodCloner.java   
private static void copyHttpMethodBase(
  HttpMethodBase m, HttpMethodBase copy) {
    try {
        copy.setParams((HttpMethodParams)m.getParams().clone());
    } catch (CloneNotSupportedException e) {
        // Should never happen
    }
}
项目:cloud-meter    文件:HTTPHC3Impl.java   
/**
 * Calculate response headers size
 * 
 * @return the size response headers (in bytes)
 */
private static int calculateHeadersSize(HttpMethodBase httpMethod) {
    int headerSize = httpMethod.getStatusLine().toString().length()+2; // add a \r\n
    Header[] rh = httpMethod.getResponseHeaders();
    for (Header responseHeader : rh) {
        headerSize += responseHeader.toString().length(); // already include the \r\n
    }
    headerSize += 2; // last \r\n before response data
    return headerSize;
}
项目:hadoop-2.6.0-cdh5.4.3    文件:SwiftRestClient.java   
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
项目:development    文件:ProxyFilter.java   
/**
 * Will create the method and execute it. After this the method is sent to a
 * ResponseHandler that is returned.
 * 
 * @param httpRequest
 *            Request we are receiving from the client
 * @param url
 *            The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException
 *             If the method specified by the request isn't handled
 * @throws IOException
 *             When there is a problem with the streams
 * @throws HttpException
 *             The httpclient can throw HttpExcetion when executing the
 *             method
 */
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory
            .createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException(
                    "Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}
项目:sourcod    文件:Tool12306Util.java   
/**
 * 
 * 设置请求头方法
 * 
 * @author zcj
 * @param hmb GetMethod or PostMethod
 * @time 2016-10-13 09:51:18
 * 
 */
static void setHeader(HttpMethodBase hmb) {
    hmb.addRequestHeader("Cache-Control", "no-cache");
    hmb.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    hmb.addRequestHeader("Accept-Encoding", "gzip, deflate, sdch");
    hmb.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
    hmb.addRequestHeader("Cache-Control", "max-age=0");
    hmb.addRequestHeader("Connection", "Keep-Alive");
    hmb.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    hmb.addRequestHeader("Host", "kyfw.12306.cn");
    hmb.addRequestHeader("Upgrade-Insecure-Requests", "1");
    hmb.addRequestHeader("Referer", "https://kyfw.12306.cn/otn/login/init");
    hmb.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
}
项目:paxml    文件:HttpTag.java   
private HttpMethodBase setHeader(HttpMethodBase method) {
    Map<String, List<String>> value = getNameValuePairs(header, "header");
    if (value != null) {
        for (Map.Entry<String, List<String>> entry : value.entrySet()) {
            for (String v : entry.getValue()) {
                method.addRequestHeader(entry.getKey(), v);
            }
        }
    } else if (header != null) {
        throw new PaxmlRuntimeException("Header should be key-value pairs but got: " + header);
    }
    return method;
}
项目:paxml    文件:HttpTag.java   
private HttpMethodBase setQueryString(HttpMethodBase method) {
    Map<String, List<String>> value = getNameValuePairs(query, "query");
    if (value != null) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, List<String>> entry : value.entrySet()) {
            for (String v : entry.getValue()) {
                pairs.add(new NameValuePair(entry.getKey(), v));
            }
        }
        method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()]));
    } else if (query != null) {
        method.setQueryString(query.toString());
    }
    return method;

}
项目:picframe    文件:OwnCloudClient.java   
/**
 * Requests the received method with the received timeout (milliseconds).
 * 
 * Executes the method through the inherited HttpClient.executedMethod(method).
 * 
 * Sets the socket and connection timeouts only for the method received.
 * 
 * The timeouts are both in milliseconds; 0 means 'infinite'; 
 * < 0 means 'do not change the default'
 *
 * @param method                HTTP method request.
 * @param readTimeout           Timeout to set for data reception
 * @param connectionTimeout     Timeout to set for connection establishment
 */
public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws IOException {

    int oldSoTimeout = getParams().getSoTimeout();
    int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
    try {
        if (readTimeout >= 0) { 
            method.getParams().setSoTimeout(readTimeout);   // this should be enough...
            getParams().setSoTimeout(readTimeout);          // ... but HTTPS needs this
        }
        if (connectionTimeout >= 0) {
            getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        }
        return executeMethod(method);
    } finally {
        getParams().setSoTimeout(oldSoTimeout);
        getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
    }
}
项目:ShoppingMall    文件:CommonsClientHttpRequestFactory.java   
/**
 * 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 HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
        case GET:
            return new GetMethod(uri);
        case DELETE:
            return new DeleteMethod(uri);
        case HEAD:
            return new HeadMethod(uri);
        case OPTIONS:
            return new OptionsMethod(uri);
        case POST:
            return new PostMethod(uri);
        case PUT:
            return new PutMethod(uri);
        case TRACE:
            return new TraceMethod(uri);
        default:
            throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}
项目:Wilma    文件:WilmaHttpClientTest.java   
@Override
public int executeMethod(HttpMethod method) {
    try {
        Field responseBody = HttpMethodBase.class.getDeclaredField("responseBody");
        responseBody.setAccessible(true);
        responseBody.set(method, expectedResponseBody.getBytes());
    } catch (Exception e) {
        throw new RuntimeException("Exception setting response stream", e);
    }
    return expectedResponseStatus;
}