若在测试阶段可以先用chrome里的postman做发送和接受api的测试,非常方便
httpclient get 方法:
public byte[] doHttpsGetXmlToBytesWithCookie(HttpContext httpContext, String url) {
if (url == null && url.trim().equals("")) {return null;
}
HttpClient httpClient = getNewHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/*+xml;version=5.1");//反馈内容的接收方式
InputStream in = null;
try {
HttpResponse response = httpClient.execute(httpGet, httpContext);
_LOG.info("status code: {}", response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
in = entity.getContent();
byte[] byteData = input2byte(in);
return byteData;
} else {
vCloudExceptionsHandler
.customVcloudExceptions(String.valueOf(response.getStatusLine().getStatusCode()));
_LOG.info(response.getStatusLine().toString());
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} finally {
httpGet.releaseConnection();
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
return null;
}
httpclient post方法:
public byte[] doHttpsPostXmlToBytesWithCookieAndRequestBody(HttpContext httpContext, String url,
String contentType, String requestBody) {
HttpClient httpClient = getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Accept", "application/*+xml;version=5.1");//反馈内容的接收方式
httpPost.addHeader("Content-Type", "application/vnd.vmware.vcloud.undeployVAppParams+xml");//发送的内容为xml格式
// Construct a string entity 发送xml格式的内容
StringEntity ent = null;
try {
ent = new StringEntity(requestBody);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Set XML entity
httpPost.setEntity(ent);
InputStream in = null;
try {
HttpResponse response = httpClient.execute(httpPost, httpContext);
if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202) {
HttpEntity entity = response.getEntity();
in = entity.getContent();
byte[] byteData = input2byte(in);
return byteData;
} else {
vCloudExceptionsHandler
.customVcloudExceptions(String.valueOf(response.getStatusLine().getStatusCode()));
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} finally {
httpPost.releaseConnection();
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
return null;
}