类org.apache.commons.httpclient.HttpMethod源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.HttpMethod的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cymbal   文件: GrafanaDashboardServiceImpl.java
private void doHttpAPI(HttpMethod method) throws MonitorException {
    // 拼装http post请求,调用grafana http api建立dashboard
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setConnectionManagerTimeout(Constant.Http.CONN_TIMEOUT);
    httpclient.getParams().setSoTimeout(Constant.Http.SO_TIMEOUT);

    // api key
    method.setRequestHeader("Authorization", String.format("Bearer %s", grafanaApiKey));
    try {

        int statusCode = httpclient.executeMethod(method);
        // 若http请求失败
        if (statusCode != Constant.Http.STATUS_OK) {
            String responseBody = method.getResponseBodyAsString();
            throw new MonitorException(responseBody);
        }
    } catch (Exception e) {
        if (e instanceof MonitorException) {
            throw (MonitorException) e;
        } else {
            new MonitorException(e);
        }
    } finally {
        method.releaseConnection();
    }
}
 
源代码2 项目: wpcleaner   文件: BasicRestApiResult.java
/**
 * Create an HttpMethod.
 * 
 * @param properties Properties to drive the API.
 * @param path Path to REST API method.
 * @param param Parameter for REST API method.
 * @return HttpMethod.
 */
protected HttpMethod createHttpMethod(
    Map<String, String> properties, String path, String param) {
  String encodedPath = path;
  if ((param != null) && !param.isEmpty()) {
    encodedPath += "/" + param;
    // NOTE: Do not encode, doesn't work with titles like Sergueï Chakourov
    /*try {
      encodedPath += "/" + URLEncoder.encode(param, "UTF8");
    } catch (UnsupportedEncodingException e) {
      // Nothing
    }*/
  }
  return Hc3HttpUtils.createHttpMethod(
      getWiki().getSettings().getHostURL(true) + "/" + encodedPath,
      properties, false);
}
 
源代码3 项目: davmail   文件: ExchangeFormAuthenticator.java
protected String getAbsoluteUri(HttpMethod method, String path) throws URIException {
    URI uri = method.getURI();
    if (path != null) {
        // reset query string
        uri.setQuery(null);
        if (path.startsWith("/")) {
            // path is absolute, replace method path
            uri.setPath(path);
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            return path;
        } else {
            // relative path, build new path
            String currentPath = method.getPath();
            int end = currentPath.lastIndexOf('/');
            if (end >= 0) {
                uri.setPath(currentPath.substring(0, end + 1) + path);
            } else {
                throw new URIException(uri.getURI());
            }
        }
    }
    return uri.getURI();
}
 
private String getHost(HttpMethod httpMethod, HttpConnection httpConnection) {
    try {
        final URI uri = httpMethod.getURI();
        // if uri have schema
        if (uri.isAbsoluteURI()) {
            return HttpClient3RequestWrapper.getEndpoint(uri.getHost(), uri.getPort());
        }
        if (httpConnection != null) {
            final String host = httpConnection.getHost();
            final int port = HttpClient3RequestWrapper.getPort(httpConnection);
            return HttpClient3RequestWrapper.getEndpoint(host, port);
        }
    } catch (Exception e) {
        if (isDebug) {
            logger.debug("Failed to get host. httpMethod={}", httpMethod, e);
        }
    }
    return null;
}
 
源代码5 项目: boubei-tss   文件: Filter5HttpProxy.java
/**
 * <p>
 * 处理请求自动转向问题
 * </p>
 * @param appServer
 * @param response
 * @param client
 * @param httppost
 * @throws IOException
 * @throws BusinessServletException
 */
private void dealWithRedirect(AppServer appServer, HttpServletResponse response, HttpClient client, HttpMethod httpMethod) 
           throws IOException, BusinessServletException {
    
	Header location = httpMethod.getResponseHeader("location");
	httpMethod.releaseConnection();
	
	if ( location == null || EasyUtils.isNullOrEmpty(location.getValue()) ) {
		throw new BusinessServletException(appServer.getName() + "(" + appServer.getCode() + ")返回错误的自动转向地址信息");
	}
	
	String redirectURI = location.getValue();
       GetMethod redirect = new GetMethod(redirectURI);
       try {
           client.executeMethod(redirect); // 发送Get请求
           
           transmitResponse(appServer, response, client, redirect);
           
       } finally {
           redirect.releaseConnection();
       }
}
 
/**
 * Test create target.
 * 
 * @throws Exception
 */
public void testSuccessfulVerifyTargetOverHttp() throws Exception
{
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
    assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
    assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
    assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
    assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
 
源代码7 项目: olat   文件: CoursesITCase.java
@Test
public void testGetCourses() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/repo/courses", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<CourseVO> courses = parseCourseArray(body);
    assertNotNull(courses);
    assertTrue(courses.size() >= 2);

    CourseVO vo1 = null;
    CourseVO vo2 = null;
    for (final CourseVO course : courses) {
        if (course.getTitle().equals("courses1")) {
            vo1 = course;
        } else if (course.getTitle().equals("courses2")) {
            vo2 = course;
        }
    }
    assertNotNull(vo1);
    assertEquals(vo1.getKey(), course1.getResourceableId());
    assertNotNull(vo2);
    assertEquals(vo2.getKey(), course2.getResourceableId());
}
 
源代码8 项目: knopflerfish.org   文件: HttpClientConnection.java
public long getHeaderFieldDate(String key, long def) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

  if (head == null) {
    return def;
  }

  try {
    Date date = DateUtil.parseDate(head.getValue());
    return date.getTime();

  } catch (DateParseException e) {
    return def;
  }
}
 
源代码9 项目: alfresco-core   文件: AbstractHttpClient.java
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;
    }
}
 
源代码10 项目: JavaChatterRESTApi   文件: ChatterCommands.java
/**
 * <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
 * String (No validation is done on this).</p>
 *
 * <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
 *
 * @param uri The full URI which we will post to
 * @param message A properly formatted JSON message. UTF-8 is expected
 * @param image A complete instance of ImageAttachment object
 * @throws IOException
 */
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
    PostMethod post = new PostMethod(uri);

    StringPart bodyPart = new StringPart("json", message);
    bodyPart.setContentType("application/json");

    FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
    filePart.setContentType(image.retrieveContentType());

    Part[] parts = {
            bodyPart,
            filePart,
    };

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    return post;
}
 
源代码11 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
源代码12 项目: diamond   文件: DefaultDiamondSubscriber.java
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // 设置HttpMethod的参数
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());
}
 
源代码13 项目: hadoop   文件: SwiftInvalidResponseException.java
public SwiftInvalidResponseException(String message,
                                     String operation,
                                     URI uri,
                                     HttpMethod method) {
  super(message);
  this.statusCode = method.getStatusCode();
  this.operation = operation;
  this.uri = uri;
  String bodyAsString;
  try {
    bodyAsString = method.getResponseBodyAsString();
    if (bodyAsString == null) {
      bodyAsString = "";
    }
  } catch (IOException e) {
    bodyAsString = "";
  }
  this.body = bodyAsString;
}
 
源代码14 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testRemoveTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
源代码15 项目: olat   文件: UserMgmtITCase.java
@Test
public void testGetUserNotAdmin() throws IOException {
    final HttpClient c = loginWithCookie("rest-one", "A6B7C8");

    final HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO vo = parse(body, UserVO.class);

    assertNotNull(vo);
    assertEquals(vo.getKey(), id2.getKey());
    assertEquals(vo.getLogin(), id2.getName());
    // no properties for security reason
    assertTrue(vo.getProperties().isEmpty());
}
 
源代码16 项目: development   文件: RequestHandlerBase.java
/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * 
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
        
        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            } 
        } 
    } 
    
    setProxySpecificHeaders(method, request);
}
 
源代码17 项目: cloudstack   文件: StressTestDirectAttach.java
private static String executeRegistration(String server, String username, String password) throws HttpException, IOException {
    String url = server + "?command=registerUserKeys&id=" + s_userId.get().toString();
    s_logger.info("registering: " + username);
    String returnValue = null;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] {"apikey", "secretkey"});
        s_apiKey.set(requestKeyValues.get("apikey"));
        returnValue = requestKeyValues.get("secretkey");
    } else {
        s_logger.error("registration failed with error code: " + responseCode);
    }
    return returnValue;
}
 
源代码18 项目: knopflerfish.org   文件: HttpClientConnection.java
public String getHeaderField(int nth)
// throws IOException TODO: doesn't this one throw exceptions??
{
  try {
    HttpMethod res = getResult(true);
    Header[] hs = res.getResponseHeaders();

    if (hs.length > nth && nth >= 0) {
      return hs[nth].getValue();
    } else {
      return null;
    }
  } catch (IOException e) {
    return null;
  }
}
 
源代码19 项目: cloudstack   文件: BigSwitchBcfApi.java
protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException {
    String url;
    try {
        url = new URL(S_PROTOCOL, host, port, uri).toString();
    } catch (MalformedURLException e) {
        S_LOGGER.error("Unable to build Big Switch API URL", e);
        throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchBcfApiException("Requesting unknown method type");
    }
}
 
@Test
public void charge_communicationFailureDetailedInfo_Bug8712()
        throws Exception {
    // setup
    ChargingData chargingData = createChargingData();
    RequestData requestData = createRequestData(DIRECT_DEBIT);
    PostMethodStub.setStubReturnValue(sampleResponse);
    when(
            Integer.valueOf(httpClientMock
                    .executeMethod(any(HttpMethod.class)))).thenThrow(
            new IOException());
    // Check error message provides details in case of communication failure
    try {
        psp.charge(requestData, chargingData);
        Assert.fail(PSPCommunicationException.class.getName() + " expected");
    } catch (PSPCommunicationException pspEx) {
        final String ERROR_MSG = pspEx.getMessage();
        Assert.assertTrue(ERROR_MSG.indexOf("[Details]") > 0);
        Assert.assertTrue(ERROR_MSG.indexOf(XML_URL) > 0);
        Assert.assertTrue(ERROR_MSG
                .indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_CHANNEL) > 0);
        Assert.assertTrue(ERROR_MSG
                .indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_LOGIN) > 0);
    }
}
 
源代码21 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testAddTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
源代码22 项目: yeti   文件: NetworkTools.java
public static String getHTMLFromUrl(String url) {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    String response = "";
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        Logger.getLogger("networkTools.getHTMLFromUrl").log(Level.SEVERE, null, e);
    } finally {
        method.releaseConnection();
    }
    return response;
}
 
源代码23 项目: olat   文件: UserMgmtITCase.java
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawJsonUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyJsons = method.getResponseBodyAsString();
    System.out.println("Users JSON");
    System.out.println(bodyJsons);
    System.out.println("Users JSON");
}
 
源代码24 项目: knopflerfish.org   文件: HttpClientConnection.java
public String getType() {
  try {
    HttpMethod res = getResult(true);
    Header head = res.getResponseHeader("Content-Type") ;

    if (head == null) {
      return null;
    }

    return head.getValue();
  } catch (IOException e) {
    return null;
  }
}
 
源代码25 项目: davmail   文件: ExchangeFormAuthenticator.java
protected void checkFormLoginQueryString(HttpMethod logonMethod) throws DavMailAuthenticationException {
    String queryString = logonMethod.getQueryString();
    if (queryString != null && (queryString.contains("reason=2") || queryString.contains("reason=4"))) {
        logonMethod.releaseConnection();
        throwAuthenticationFailed();
    }
}
 
源代码26 项目: boubei-tss   文件: Filter5HttpProxy.java
/**
 * <p>
 * 请求转向不同同服务器的其他应用
 * </p>
 * @param appServer
 * @param req
 * @param response
 * @throws IOException
 * @throws BusinessServletException
 */
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
       HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
	HttpState httpState = client.getState();
	
	/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
       boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
       String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
       String domain = appServer.getDomain();
       String path   = appServer.getPath(); 
       if (Context.isOnline()) {
           httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
       }
       if (Environment.getSessionId() != null) {
           httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
       }
	
	HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
	try {
		// 请求
           int statusCode = client.executeMethod(httpMethod);
		if (statusCode == HttpStatus.SC_OK) {
			// 转发返回信息
			transmitResponse(appServer, response, client, httpMethod);
		} 
		else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		    
			dealWithRedirect(appServer, response, client, httpMethod);
		} 
		
	} finally {
		httpMethod.releaseConnection();
	}
}
 
/**
 *
 * @param methodName String
 * @param response int
 * @param method HttpMethod
 */
private void checkResponseStatus(String methodName, int response, HttpMethod method)
{
    if (response != 200)
    {
        Throwable error = null;
        try
        {
            log.error("Received \"unsuccessful\" response code from target server: " + response);
            String errorPayload = method.getResponseBodyAsString();
            JSONObject errorObj = new JSONObject(errorPayload);
            error = rehydrateError(errorObj);
        }
        catch (Exception ex)
        {
            throw new TransferException(MSG_UNSUCCESSFUL_RESPONSE, new Object[] {methodName, response});
        }
        if ((error != null) && TransferException.class.isAssignableFrom(error.getClass()))
        {
            throw (TransferException)error;
        }
        else
        {
            throw new TransferException(MSG_UNSUCCESSFUL_RESPONSE, new Object[] {methodName, response});
        }
    }
}
 
源代码28 项目: olat   文件: MorphologicalServiceDEImpl.java
private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&" + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }
    method.setQueryString(new NameValuePair[] { posValues, wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}
 
源代码29 项目: zap-extensions   文件: CloudMetadataScanner.java
private static HttpMethod createRequestMethod(
        HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException {
    HttpMethod httpMethod = new ZapGetMethod();
    httpMethod.setURI(header.getURI());
    httpMethod.setParams(params);
    params.setVersion(HttpVersion.HTTP_1_1);

    String msg = header.getHeadersAsString();

    String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg);
    String token = null;
    String name = null;
    String value = null;

    int pos = 0;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
 
public void testGetStatusErrorRehydration() throws Exception
{
    final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer();
    final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"}); 
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable
        {
            JSONObject progressObject = new JSONObject();
            progressObject.put("transferId", "mytransferid");
            progressObject.put("status", Status.ERROR);
            progressObject.put("currentPosition", 1);
            progressObject.put("endPosition", 10);
            JSONObject errorObject = errorSerializer.serialize(expectedException);
            progressObject.put("error", errorObject);
            return progressObject.toString();
        }
    }).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString();
    
    Transfer transfer = new Transfer();
    transfer.setTransferId("mytransferid");
    transfer.setTransferTarget(target);
    TransferProgress progress = transmitter.getStatus(transfer);
    assertTrue(progress.getError() != null);
    assertEquals(expectedException.getClass(), progress.getError().getClass());
    TransferException receivedException = (TransferException)progress.getError();
    assertEquals(expectedException.getMsgId(), receivedException.getMsgId());
    assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), receivedException.getMsgParams()));
}
 
 类方法
 同包方法