类org.apache.commons.httpclient.methods.GetMethod源码实例Demo

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

源代码1 项目: otroslogviewer   文件: JumpToCodeClient.java
private HttpMethod buildMethod(String url, LocationInfo locationInfo, HttpOperation httpOperation) {
  HttpMethod method = new GetMethod(url);
  ArrayList<NameValuePair> list = new ArrayList<>(5);
  list.add(new NameValuePair("o", httpOperation.getOperation()));

  locationInfo.getPackageName().ifPresent(p -> list.add(new NameValuePair("p", p)));
  locationInfo.getClassName().ifPresent(p -> list.add(new NameValuePair("c", p)));
  locationInfo.getFileName().ifPresent(p -> list.add(new NameValuePair("f", p)));
  locationInfo.getMessage().ifPresent(m -> list.add(new NameValuePair("m", m)));
  locationInfo.getLineNumber().map(i -> Integer.toString(i)).ifPresent(l -> list.add(new NameValuePair("l", l)));


  NameValuePair[] pair = list.toArray(new NameValuePair[0]);

  method.setQueryString(pair);
  return method;
}
 
源代码2 项目: document-management-system   文件: MailUtils.java
/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 */
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
	HttpClient httpclient = new HttpClient();

	// Prepare a request object
	HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
	method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)});
	httpclient.executeMethod(method);
	InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
	StringWriter sw = new StringWriter();
	int c;
	while ((c = isr.read()) != -1)
		sw.write(c);
	isr.close();
	method.releaseConnection();

	return sw.toString();
}
 
源代码3 项目: submarine   文件: SubmarineServerTest.java
@Test
// SUBMARINE-422. Fix refreshing page returns 404 error
public void testRefreshingURL() throws IOException {
  ArrayList<String> arrUrls = new ArrayList();
  arrUrls.add("/user/login");
  arrUrls.add("/workbench/manager/user");

  for (int i = 0; i < arrUrls.size(); i++) {
    GetMethod response = httpGet(arrUrls.get(i));
    LOG.info(response.toString());

    String requestBody = response.getResponseBodyAsString();
    LOG.info(requestBody);
    assertFalse(requestBody.contains("Error 404 Not Found"));
  }
}
 
源代码4 项目: OfficeAutomatic-System   文件: HttpUtil.java
public static String sendGet(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建GET请求方法实例对象
    GetMethod getMethod = new GetMethod(urlParam);
    // 设置post请求超时时间
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    getMethod.addRequestHeader("Content-Type", "application/json");

    httpClient.executeMethod(getMethod);

    String result = getMethod.getResponseBodyAsString();
    getMethod.releaseConnection();
    return result;
}
 
源代码5 项目: openemm   文件: NetworkUtil.java
public static byte[] loadUrlData(String url) throws Exception {
	HttpClient httpClient = new HttpClient();
	setHttpClientProxyFromSystem(httpClient, url);
	GetMethod get = new GetMethod(url);		
	get.setFollowRedirects(true);
	
	try {			
		httpClient.getParams().setParameter("http.connection.timeout", 5000);
		int httpReturnCode = httpClient.executeMethod(get); 

		if (httpReturnCode == 200) {
			// Don't use get.getResponseBody, it causes a warning in log
			try (InputStream inputStream = get.getResponseBodyAsStream()) {
				return IOUtils.toByteArray(inputStream);
			}
		} else {
			throw new Exception("ERROR: Received httpreturncode " + httpReturnCode);
		}
	} finally {
		get.releaseConnection();
	}
}
 
源代码6 项目: olat   文件: CourseGroupMgmtITCase.java
@Test
public void testGetCourseGroups() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<GroupVO> vos = parseGroupArray(body);
    assertNotNull(vos);
    assertEquals(2, vos.size());// g1 and g2
    assertTrue(vos.get(0).getKey().equals(g1.getKey()) || vos.get(0).getKey().equals(g2.getKey()));
    assertTrue(vos.get(1).getKey().equals(g1.getKey()) || vos.get(1).getKey().equals(g2.getKey()));
}
 
源代码7 项目: 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;
}
 
源代码8 项目: MyVirtualDirectory   文件: GetSSLCert.java
public static javax.security.cert.X509Certificate getCert(String host, int port) {
	GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
	Protocol myhttps = new Protocol("https", certFactory, port);
	HttpClient httpclient = new HttpClient();
	httpclient.getHostConfiguration().setHost(host, port, myhttps);
	GetMethod httpget = new GetMethod("/");
	try {
	  httpclient.executeMethod(httpget);
	  //System.out.println(httpget.getStatusLine());
	} catch (Throwable t) {
		//do nothing
	}
	
	finally {
	  httpget.releaseConnection();
	}
	
	return certFactory.getCertificate();
}
 
源代码9 项目: boost   文件: EndpointIT.java
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL + "/hello");

    try {
        int statusCode = client.executeMethod(method);

        assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

        String response = method.getResponseBodyAsString(10000);

        assertTrue("Unexpected response body",
                response.contains("Hello World From Your Friends at Liberty Boost EE!"));
    } finally {
        method.releaseConnection();
    }
}
 
源代码10 项目: zeppelin   文件: HeliumRestApiTest.java
@Test
public void testVisualizationPackageOrder() throws IOException {
  GetMethod get1 = httpGet("/helium/order/visualization");
  assertThat(get1, isAllowed());
  Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body1 = (List<Object>) resp1.get("body");
  assertEquals(body1.size(), 0);

  //We assume allPackages list has been refreshed before sorting
  helium.getAllPackageInfo();

  String postRequestJson = "[name2, name1]";
  PostMethod post = httpPost("/helium/order/visualization", postRequestJson);
  assertThat(post, isAllowed());
  post.releaseConnection();

  GetMethod get2 = httpGet("/helium/order/visualization");
  assertThat(get2, isAllowed());
  Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body2 = (List<Object>) resp2.get("body");
  assertEquals(body2.size(), 2);
  assertEquals(body2.get(0), "name2");
  assertEquals(body2.get(1), "name1");
}
 
源代码11 项目: zeppelin   文件: AbstractTestRestApi.java
protected static boolean checkIfServerIsRunning() {
  GetMethod request = null;
  boolean isRunning;
  try {
    request = httpGet("/version");
    isRunning = request.getStatusCode() == 200;
  } catch (IOException e) {
    LOG.error("AbstractTestRestApi.checkIfServerIsRunning() fails .. ZeppelinServer is not " +
            "running");
    isRunning = false;
  } finally {
    if (request != null) {
      request.releaseConnection();
    }
  }
  return isRunning;
}
 
源代码12 项目: swellrt   文件: SolrSearchProviderImpl.java
private JsonArray sendSearchRequest(String solrQuery,
    Function<InputStreamReader, JsonArray> function) throws IOException {
  JsonArray docsJson;
  GetMethod getMethod = new GetMethod();
  HttpClient httpClient = new HttpClient();
  try {
    getMethod.setURI(new URI(solrQuery, false));
    int statusCode = httpClient.executeMethod(getMethod);
    docsJson = function.apply(new InputStreamReader(getMethod.getResponseBodyAsStream()));
    if (statusCode != HttpStatus.SC_OK) {
      LOG.warning("Failed to execute query: " + solrQuery);
      throw new IOException("Search request status is not OK: " + statusCode);
    }
  } finally {
    getMethod.releaseConnection();
  }
  return docsJson;
}
 
源代码13 项目: development   文件: PortFactory.java
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
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();
}
 
源代码14 项目: zeppelin   文件: DirAccessTest.java
@Test
public void testDirAccessOk() throws Exception {
  synchronized (this) {
    try {
      System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED
              .getVarName(), "true");
      AbstractTestRestApi.startUp(DirAccessTest.class.getSimpleName());
      HttpClient httpClient = new HttpClient();
      GetMethod getMethod = new GetMethod(getUrlToTest() + "/app/");
      LOG.info("Invoke getMethod");
      httpClient.executeMethod(getMethod);
      assertEquals(getMethod.getResponseBodyAsString(),
              HttpStatus.SC_OK, getMethod.getStatusCode());
    } finally {
      AbstractTestRestApi.shutDown();
    }
  }
}
 
源代码15 项目: olat   文件: UserMgmtITCase.java
@Test
public void testFindUsersByLogin() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"), new NameValuePair("authProvider", "OLAT") });
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final String[] authProviders = new String[] { "OLAT" };
    final List<Identity> identities = securityManager.getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
    boolean onlyLikeAdmin = true;
    for (final UserVO vo : vos) {
        if (!vo.getLogin().startsWith("administrator")) {
            onlyLikeAdmin = false;
        }
    }
    assertTrue(onlyLikeAdmin);
}
 
源代码16 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testGetGroupInfos() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/infos";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final GroupInfoVO vo = parse(body, GroupInfoVO.class);
    assertNotNull(vo);
    assertEquals(Boolean.TRUE, vo.getHasWiki());
    assertEquals("<p>Hello world</p>", vo.getNews());
    assertNotNull(vo.getForumKey());
}
 
源代码17 项目: cloudstack   文件: UriUtils.java
public static InputStream getInputStreamFromUrl(String url, String user, String password) {

        try {
            Pair<String, Integer> hostAndPort = validateUrl(url);
            HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                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.
            GetMethod method = new GetMethod(url);
            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 (Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
源代码18 项目: neoscada   文件: HdHttpClient.java
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 ();
    }
}
 
源代码19 项目: cloudstack   文件: User.java
public void launchUser() throws IOException {
    String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8");
    this.encryptedPassword = TestClientWithAPI.createMD5Password(this.getPassword());
    String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8");
    String url =
        this.server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword +
            "&firstname=Test&lastname=Test&[email protected]&domainId=1";
    String userIdStr = 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> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] {"id"});
        userIdStr = userIdValues.get("id");
        if ((userIdStr != null) && (Long.parseLong(userIdStr) != -1)) {
            this.setUserId(userIdStr);
        }
    }
}
 
源代码20 项目: h2o-2   文件: WebAPI.java
/**
 * Exports a model to a JSON file.
 */
static void exportModel() throws Exception {
  HttpClient client = new HttpClient();
  GetMethod get = new GetMethod(URL + "/2/ExportModel.json?model=MyInitialNeuralNet");
  int status = client.executeMethod(get);
  if( status != 200 )
    throw new Exception(get.getStatusText());
  JsonObject response = (JsonObject) new JsonParser().parse(new InputStreamReader(get.getResponseBodyAsStream()));
  JsonElement model = response.get("model");
  JsonWriter writer = new JsonWriter(new FileWriter(JSON_FILE));
  writer.setLenient(true);
  writer.setIndent("  ");
  Streams.write(model, writer);
  writer.close();
  get.releaseConnection();
}
 
源代码21 项目: zeppelin   文件: HeliumRestApiTest.java
@Test
public void testEnableDisablePackage() throws IOException {
  String packageName = "name1";
  PostMethod post1 = httpPost("/helium/enable/" + packageName, "");
  assertThat(post1, isAllowed());
  post1.releaseConnection();

  GetMethod get1 = httpGet("/helium/package/" + packageName);
  Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<StringMap<Object>> body1 = (List<StringMap<Object>>) resp1.get("body");
  assertEquals(body1.get(0).get("enabled"), true);

  PostMethod post2 = httpPost("/helium/disable/" + packageName, "");
  assertThat(post2, isAllowed());
  post2.releaseConnection();

  GetMethod get2 = httpGet("/helium/package/" + packageName);
  Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<StringMap<Object>> body2 = (List<StringMap<Object>>) resp2.get("body");
  assertEquals(body2.get(0).get("enabled"), false);
}
 
源代码22 项目: orion.server   文件: GetRouteByGuidCommand.java
public ServerStatus _doIt() {
	try {
		URI targetURI = URIUtil.toURI(getCloud().getUrl());

		// Get the app
		URI appsURI = targetURI.resolve("/v2/routes/" + routeGuid);
		GetMethod getRoutesMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getRoutesMethod, getCloud());
		if (!confStatus.isOK())
			return confStatus;

		ServerStatus getStatus = HttpUtil.executeMethod(getRoutesMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject routeJSON = getStatus.getJsonData();
		this.route = new Route().setCFJSON(routeJSON);

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.route.toJSON());
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
源代码23 项目: 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;
}
 
源代码24 项目: samza   文件: YarnRestJobStatusProvider.java
/**
 * Issues a HTTP Get request to the provided url and returns the response
 * @param requestUrl the request url
 * @return the response
 * @throws IOException if there are problems with the http get request.
 */
byte[] httpGet(String requestUrl)
    throws IOException {
  GetMethod getMethod = new GetMethod(requestUrl);
  try {
    int responseCode = this.httpClient.executeMethod(getMethod);
    LOGGER.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
    byte[] response = getMethod.getResponseBody();
    if (responseCode != HttpStatus.SC_OK) {
      throw new SamzaException(
          String.format("Received response code: %s for get request on: %s, with message: %s.", responseCode,
              requestUrl, StringUtils.newStringUtf8(response)));
    }
    return response;
  } finally {
    getMethod.releaseConnection();
  }
}
 
源代码25 项目: olat   文件: CoursesResourcesFoldersITCase.java
@Test
public void testGetFilesDeeper() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir").build();
    final GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final String body = method.getResponseBodyAsString();
    final List<LinkVO> links = parseLinkArray(body);
    assertNotNull(links);
    assertEquals(1, links.size());
    assertEquals("3_singlepage.html", links.get(0).getTitle());
}
 
源代码26 项目: olat   文件: AuthenticationITCase.java
@Test
public void testWrongPassword() throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("administrator").queryParam("password", "blabla").build();
    final GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true);
    final HttpClient c = getHttpClient();
    final int code = c.executeMethod(method);
    assertEquals(401, code);
}
 
源代码27 项目: 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;
}
 
源代码28 项目: zeppelin   文件: ZeppelinRestApiTest.java
@Test
public void testGetParagraph() throws IOException {
  Note note = null;
  try {
    note = TestUtils.getInstance(Notebook.class).createNote("note1_testGetParagraph", anonymous);

    Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
    p.setTitle("hello");
    p.setText("world");
    TestUtils.getInstance(Notebook.class).saveNote(note, anonymous);

    GetMethod get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p.getId());
    LOG.info("testGetParagraph response\n" + get.getResponseBodyAsString());
    assertThat("Test get method: ", get, isAllowed());
    get.releaseConnection();

    Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(),
            new TypeToken<Map<String, Object>>() {}.getType());

    assertNotNull(resp);
    assertEquals("OK", resp.get("status"));

    Map<String, Object> body = (Map<String, Object>) resp.get("body");

    assertEquals(p.getId(), body.get("id"));
    assertEquals("hello", body.get("title"));
    assertEquals("world", body.get("text"));
  } finally {
    //cleanup
    if (null != note) {
      TestUtils.getInstance(Notebook.class).removeNote(note, anonymous);
    }
  }
}
 
public void LUDOTODOtestWithInvalidInboundIp() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrlForHostIP("/test-ssl").toString());
  int httpCode = httpClient.executeMethod(get);
  assertEquals(403, httpCode);
}
 
源代码30 项目: rome   文件: ClientMediaEntry.java
private InputStream getResourceAsStream() throws ProponoException {
    if (getEditURI() == null) {
        throw new ProponoException("ERROR: not yet saved to server");
    }
    final GetMethod method = new GetMethod(((Content) getContents()).getSrc());
    try {
        getCollection().getHttpClient().executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status=" + method.getStatusCode());
        }
        return method.getResponseBodyAsStream();
    } catch (final IOException e) {
        throw new ProponoException("ERROR: getting media entry", e);
    }
}
 
 类方法
 同包方法