下面列出了怎么用org.apache.commons.httpclient.methods.GetMethod的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
/**
* 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();
}
@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"));
}
}
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;
}
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();
}
}
@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()));
}
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;
}
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();
}
@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();
}
}
@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");
}
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;
}
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;
}
/**
* 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();
}
@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();
}
}
}
@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);
}
@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());
}
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;
}
}
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 ();
}
}
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);
}
}
}
/**
* 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();
}
@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);
}
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);
}
}
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;
}
/**
* 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();
}
}
@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());
}
@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);
}
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;
}
@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);
}
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);
}
}