下面列出了怎么用org.apache.commons.httpclient.HttpClient的API类实例代码及写法,或者点击链接到github查看源代码。
public Book getBook(String bookName) throws Exception {
String output = null;
try{
String url = "http://localhost:8080/bookservice/getbook/";
url = url + URLEncoder.encode(bookName, "UTF-8");
HttpClient client = new HttpClient();
PostMethod mPost = new PostMethod(url);
client.executeMethod( mPost );
Header mtHeader = new Header();
mtHeader.setName("content-type");
mtHeader.setValue("application/x-www-form-urlencoded");
mtHeader.setName("accept");
mtHeader.setValue("application/xml");
mPost.addRequestHeader(mtHeader);
client.executeMethod(mPost);
output = mPost.getResponseBodyAsString( );
mPost.releaseConnection( );
System.out.println("out : " + output);
}catch(Exception e){
throw new Exception("Exception in retriving group page info : " + e);
}
return null;
}
@Test
public void testCreateEmptyCourse() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
.build();
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
final CourseVO course = parse(body, CourseVO.class);
assertNotNull(course);
assertEquals("course3", course.getTitle());
// check repository entry
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
assertNotNull(re);
assertNotNull(re.getOlatResource());
assertNotNull(re.getOwnerGroup());
}
@Test
public void testServlet() throws Exception {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(URL);
try {
int statusCode = client.executeMethod(method);
assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);
String response = method.getResponseBodyAsString();
assertTrue("Unexpected response body", response.contains("Simple Servlet ran successfully"));
} finally {
method.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()));
}
@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()));
}
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "urn:getQuote");
HttpMethodParams params = new HttpMethodParams();
params.setVersion(HttpVersion.HTTP_1_1);
post.setParams(params);
HttpClient httpClient = new HttpClient();
String httpVersion = "";
try {
httpClient.executeMethod(post);
post.getResponseBodyAsString();
httpVersion = post.getStatusLine().getHttpVersion();
} finally {
post.releaseConnection();
}
Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
@Test
public void createClient_WithoutCredentials() throws Exception {
// given
System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
// when
HttpClient client = vdcClient.createHttpClient();
// then
assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
.getProxyHost());
assertEquals(HTTPS_PROXY_PORT_VALUE,
String.valueOf(client.getHostConfiguration().getProxyPort()));
assertNull(client.getState().getProxyCredentials(AuthScope.ANY));
}
@Test
public void testNormalFlow() throws HttpException, IOException, UnauthenticatedSessionException,
AuthenticationException {
IChatterData data = getMockedChatterData();
ClientSecretAuthentication auth = new ClientSecretAuthentication(data, "");
HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.executeMethod(any(PostMethod.class))).thenAnswer(
new ExecuteMethodAnswer("{\"access_token\" : \"abc\" }"));
auth.setHttpClient(mockHttpClient);
ChatterAuthToken token = auth.authenticate();
assertEquals("abc", token.getAccessToken());
}
public void testAsyncRequests_WaitUntilDone() throws Exception {
long sleepTime = 2000;
FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
ApiProxy.setDelegate(fakeApiProxy);
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
GetMethod get = new GetMethod(createUrl("/sleep").toString());
get.addRequestHeader("Use-Async-Sleep-Api", "true");
get.addRequestHeader("Sleep-Time", Long.toString(sleepTime));
long startTime = System.currentTimeMillis();
int httpCode = httpClient.executeMethod(get);
assertEquals(200, httpCode);
Header vmApiWaitTime = get.getResponseHeader(VmRuntimeUtils.ASYNC_API_WAIT_HEADER);
assertNotNull(vmApiWaitTime);
assertTrue(Integer.parseInt(vmApiWaitTime.getValue()) > 0);
long elapsed = System.currentTimeMillis() - startTime;
assertTrue(elapsed >= sleepTime);
}
@Test
public void testGetGroupInfos2() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final String request = "/groups/" + g2.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.FALSE, vo.getHasWiki());
assertNull(vo.getNews());
assertNotNull(vo.getForumKey());
}
/**
* 从配置管理WEB服务器下载规则(json表示)
*
* @param url 配置管理WEB服务器下载规则的地址
* @return json字符串
*/
private String downJson(String url) {
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 创建GET方法的实例
GetMethod method = new GetMethod(url);
try {
// 执行GetMethod
int statusCode = httpClient.executeMethod(method);
LOGGER.info("响应代码:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
LOGGER.error("请求失败: " + method.getStatusLine());
}
// 读取内容
String responseBody = new String(method.getResponseBody(), "utf-8");
return responseBody;
} catch (IOException e) {
LOGGER.error("检查请求的路径:" + url, e);
} finally {
// 释放连接
method.releaseConnection();
}
return "";
}
@Test
public void testCreateEmptyCourse() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
.build();
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
final CourseVO course = parse(body, CourseVO.class);
assertNotNull(course);
assertEquals("course3", course.getTitle());
// check repository entry
final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
assertNotNull(re);
assertNotNull(re.getOlatResource());
assertNotNull(re.getOwnerGroup());
}
public void get() throws UnsupportedEncodingException {
HttpClient client = new HttpClient();
String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
String INFO =new URLCodec().encode("who are you","utf-8");
String requesturl = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
GetMethod getMethod = new GetMethod(requesturl);
try {
int stat = client.executeMethod(getMethod);
if (stat != HttpStatus.SC_OK)
log.error("get失败!");
byte[] responseBody = getMethod.getResponseBody();
String content=new String(responseBody ,"utf-8");
log.info(content);
}catch (Exception e){
log.error(""+e.getLocalizedMessage());
}finally {
getMethod.releaseConnection();
}
}
public static List<String> getMetalinkChecksums(String url) {
HttpClient httpClient = getHttpClient();
GetMethod getMethod = new GetMethod(url);
try {
if (httpClient.executeMethod(getMethod) == HttpStatus.SC_OK) {
InputStream is = getMethod.getResponseBodyAsStream();
Map<String, List<String>> checksums = getMultipleValuesFromXML(is, new String[] {"hash"});
if (checksums.containsKey("hash")) {
List<String> listChksum = new ArrayList<>();
for (String chk : checksums.get("hash")) {
listChksum.add(chk.replaceAll("\n", "").replaceAll(" ", "").trim());
}
return listChksum;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
}
return null;
}
@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);
}
@Test
public void testDeleteCatalogEntry() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(200, code);
method.releaseConnection();
final List<CatalogEntry> entries = catalogService.getChildrenOf(root1);
for (final CatalogEntry entry : entries) {
assertFalse(entry.getKey().equals(entry2.getKey()));
}
}
@Test
public void testServlet() throws Exception {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(URL);
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("The population of NYC is 8550405"));
} finally {
method.releaseConnection();
}
}
@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 testUpdateCourseGroup() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final GroupVO vo = new GroupVO();
vo.setKey(g1.getKey());
vo.setName("rest-g1-mod");
vo.setDescription("rest-g1 description");
vo.setMinParticipants(g1.getMinParticipants());
vo.setMaxParticipants(g1.getMaxParticipants());
vo.setType(g1.getType());
final String stringuifiedAuth = stringuified(vo);
final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
final String request = "/groups/" + g1.getKey();
final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
method.setRequestEntity(entity);
final int code = c.executeMethod(method);
assertTrue(code == 200 || code == 201);
final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
assertNotNull(bg);
assertEquals(bg.getKey(), vo.getKey());
assertEquals(bg.getName(), "rest-g1-mod");
assertEquals(bg.getDescription(), "rest-g1 description");
}
@Test
public void testAddOwner() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
method.releaseConnection();
assertEquals(200, code);
final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
boolean found = false;
for (final Identity identity : identities) {
if (identity.getKey().equals(id1.getKey())) {
found = true;
}
}
assertTrue(found);
}
private HttpClient getHttpClient() {
HttpClient client = new HttpClient();
Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
ProxyConfiguration proxy = jenkins.proxy;
if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.name, proxy.port);
String username = proxy.getUserName();
String password = proxy.getPassword();
// Consider it to be passed if username specified. Sufficient?
if (StringUtils.isNotBlank(username)) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
}
}
}
client.getParams().setConnectionManagerTimeout(timeout);
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
return client;
}
@Before
public void setUp() {
HttpClientParams hmp = mock(HttpClientParams.class);
when(_client.getParams()).thenReturn(hmp);
_api = new BigSwitchBcfApi(){
@Override
protected HttpClient createHttpClient() {
return _client;
}
@Override
protected HttpMethod createMethod(String type, String uri, int port) {
return _method;
}
};
_api.setControllerAddress("10.10.0.10");
_api.setControllerUsername("myname");
_api.setControllerPassword("mypassword");
}
@Test
public void testGetOwner() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
// admin is owner
URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(admin.getKey().toString()).build();
GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);
int code = c.executeMethod(method);
assertEquals(200, code);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final UserVO vo = parse(body, UserVO.class);
assertNotNull(vo);
// id1 is not owner
uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
method = createGet(uri, MediaType.APPLICATION_JSON, true);
code = c.executeMethod(method);
assertEquals(404, code);
}
@Test
public void testGetGroups() throws IOException {
final HttpClient c = loginWithCookie("rest-four", "A6B7C8");
final String request = "/groups";
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 List<GroupVO> groups = parseGroupArray(body);
assertNotNull(groups);
assertTrue(groups.size() >= 2);// g1, g2, g3 and g4 + from olat
final Set<Long> keys = new HashSet<Long>();
for (final GroupVO vo : groups) {
keys.add(vo.getKey());
}
assertTrue(keys.contains(g1.getKey()));
assertTrue(keys.contains(g2.getKey()));
assertFalse(keys.contains(g3.getKey()));
assertFalse(keys.contains(g4.getKey()));
}
private void setProxy(HttpClient httpClient) {
String proxyHost = AppSettings.get().get("http.proxy.host").trim();
Integer proxyPort = Integer.parseInt(AppSettings.get().get("http.proxy.port").trim());
HostConfiguration hostConfig = httpClient.getHostConfiguration();
hostConfig.setProxy(proxyHost, proxyPort);
if (!AppSettings.get().get("http.proxy.user").equals("")) {
String user;
String pwd;
org.apache.commons.httpclient.UsernamePasswordCredentials credentials;
org.apache.commons.httpclient.auth.AuthScope authscope;
user = AppSettings.get().get("http.proxy.user").trim();
pwd = AppSettings.get().get("http.proxy.password").trim();
credentials = new org.apache.commons.httpclient.UsernamePasswordCredentials(user, pwd);
authscope = new org.apache.commons.httpclient.auth.AuthScope(proxyHost, proxyPort);
httpClient.getState().setProxyCredentials(authscope, credentials);
}
}
/**
* A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
*
* @param user
* can be NULL
* @param password
* can be NULL
* @return HttpClient
*/
public static HttpClient getHttpClientInstance(String user, String password) {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionParams params = connectionManager.getParams();
// wait max 10 seconds to establish connection
params.setConnectionTimeout(10000);
// a read() call on the InputStream associated with this Socket
// will block for only this amount
params.setSoTimeout(10000);
HttpClient c = new HttpClient(connectionManager);
// use basic authentication if available
if (user != null && user.length() > 0) {
AuthScope authScope = new AuthScope(null, -1, null);
Credentials credentials = new UsernamePasswordCredentials(user, password);
c.getState().setCredentials(authScope, credentials);
}
return c;
}
@Test
public void testServlet() throws Exception {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(URL);
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();
}
}
public String getAccessTokenUserPass() {
if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
return this.oAuth2AccessToken;
}
if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
|| StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
return "";
}
try {
HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
// post development
PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));
method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
new NameValuePair("grant_type", oAuth2GrantType) };
method.setRequestBody(body);
int responseCode = client.executeMethod(method);
String responseBody = method.getResponseBodyAsString();
if (responseCode != 200) {
throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
+ ", got response code " + responseCode);
}
JSONObject accessResponse = new JSONObject(responseBody);
accessResponse.getString("access_token");
return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
} catch (Exception e) {
throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
}
}
protected static DeleteMethod httpDelete(String path, String user, String pwd) throws IOException {
LOG.info("Connecting to {}", URL + path);
HttpClient httpClient = new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(URL + path);
deleteMethod.addRequestHeader("Origin", URL);
if (userAndPasswordAreNotBlank(user, pwd)) {
deleteMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
}
httpClient.executeMethod(deleteMethod);
LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText());
return deleteMethod;
}
private HttpClient createHttpClient() {
//see http://hc.apache.org/httpclient-3.x/threading.html
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = connectionManager.getParams();
params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_HOST_CONF_KEY, 50));
params.setMaxTotalConnections(PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_TOTAL_CONF_KEY, 150));
params.setConnectionTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_TIMEOUT_CONF_KEY, 15000)); //15s
params.setSoTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_SO_TIMEOUT_CONF_KEY, 30000)); //30s
connectionManager.setParams(params);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setConnectionManagerTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_MGR_TIMEOUT_CONF_KEY, 300000)); // 5 minutes
return new HttpClient(clientParams, connectionManager);
}