本文整理汇总了Java中javax.xml.ws.http.HTTPException类的典型用法代码示例。如果您正苦于以下问题:Java HTTPException类的具体用法?Java HTTPException怎么用?Java HTTPException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HTTPException类属于javax.xml.ws.http包,在下文中一共展示了HTTPException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: shorten
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
/**
* Shortens a URL with bit.ly.
*
* @param longURL the URL to shorten.
* @return the shortened URL.
* @throws IllegalArgumentException if the long URI was invalid.
* @throws HTTPException if the bit.ly API returns a response code unlike 200 'OK'.
* @throws RuntimeException if the http request threw an unknown error.
*/
public static String shorten(String longURL) {
HttpRequest request = new HttpRequest(API_URL);
request.addParameter("access_token", Info.BITLY_TOKEN);
request.addParameter("longUrl", longURL);
request.addParameter("format", "json");
RequestResponse result;
try {
result = request.sendGETRequest();
} catch (Exception e) {
// catch 'anonymous' exceptions
throw new RuntimeException("An unknown exception occurred while fetching a bit.ly http request", e);
}
JSONObject response = new JSONObject(result.getResponse());
// check if uri was valid
if (response.getString("status_txt").equals("INVALID_URI"))
throw new IllegalArgumentException("'" + longURL + "' is not a valid URL.");
// ensure 'OK' status response
else if (response.getInt("status_code") == 400)
throw new HTTPException(response.getInt("status_code"));
// return shortened url
return response.getJSONObject("data").getString("url");
}
示例2: doRoleCommand
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) {
URI uri = UriBuilder.fromUri(serverHostname)
.path("api")
.path(API_VERSION)
.path("clusters")
.path(clusterName)
.path("services")
.path(serviceName)
.path("roleCommands")
.path(roleCommand.toString())
.build();
String body = "{ \"items\": [ \"" + roleName + "\" ] }";
LOG.info("Executing POST against " + uri + " with body " + body + "...");
ClientResponse response = client.resource(uri)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, body);
int statusCode = response.getStatus();
if (statusCode != Response.Status.OK.getStatusCode()) {
throw new HTTPException(statusCode);
}
}
示例3: sendPost
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
public void sendPost(URL url, Path content) throws IOException {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "UTF-8");
con.setDoOutput(true);
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(con.getOutputStream())) {
Files.copy(content, bufferedOutputStream);
}
int responseCode = con.getResponseCode();
StringBuilder response = readResponse(con);
if (isFailureResponseCode(responseCode)) {
throw new HTTPException(responseCode);
}
} finally {
if (con != null) {
con.disconnect();
}
}
}
示例4: sendResponse
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private void sendResponse(HttpServletResponse response, String payload, boolean json) {
try {
// Convert to JSON?
if (json) {
JSONObject jobt = XML.toJSONObject(payload);
payload = jobt.toString(3); // 3 is indentation level for nice look
}
OutputStream out = response.getOutputStream();
out.write(payload.getBytes());
out.flush();
}
catch(Exception e) {
throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
示例5: getRequest
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
/**
*
* HTTP Get request:
* GET url
*
* If the HTTP status code is not 200, this method throws
* {@link HTTPException}.
*
* @param url Url for GET request.
* @return Data sent by the server in response as byte[].
* @throws MalformedURLException
* @throws IOException
*/
public static byte[] getRequest( String url ) throws MalformedURLException, IOException
{
HttpURLConnection connection = ( HttpURLConnection ) new URL( url ).openConnection();
int response = connection.getResponseCode();
if ( response != 200 )
throw new HTTPException( response );
byte[] bytes;
String transferEncoding = connection.getHeaderField( "Transfer-Encoding" );
if ( transferEncoding != null && transferEncoding.compareToIgnoreCase( "chunked" ) == 0 )
{
ChunkedByteArrayResponseHandler handler = new ChunkedByteArrayResponseHandler( 1024 );
getRequest( connection, handler );
bytes = handler.getArray();
} else
{
int contentLength = Integer.parseInt( connection.getHeaderField( "Content-Length" ) );
bytes = new byte[ contentLength ];
getRequest( connection, new ByteArrayResponseHandler( bytes ) );
}
connection.disconnect();
return bytes;
}
示例6: getReplyFromCloudSync
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
protected MovilizerResponse getReplyFromCloudSync(MovilizerRequest request,
Integer connectionTimeoutInMillis,
Integer receiveTimeoutInMillis) {
MovilizerResponse response;
try {
setTimeout(connectionTimeoutInMillis, receiveTimeoutInMillis);
response = movilizerCloud.movilizer(request);
} catch (SOAPFaultException | HTTPException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getMessage());
}
throw new MovilizerWebServiceException(e);
} finally {
setTimeout(defaultConnectionTimeoutInMillis, defaultReceiveTimeoutInMillis);
}
if (logger.isInfoEnabled()) {
logger.info(String.format(MESSAGES.RESPONSE_RECEIVED, response.getSystemId()));
}
return response;
}
示例7: getReplyFromCloud
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
protected void getReplyFromCloud(MovilizerRequest request, Integer connectionTimeoutInMillis,
Integer receiveTimeoutInMillis,
FutureCallback<MovilizerResponse> asyncHandler) {
try {
if (logger.isDebugEnabled()) {
logger.debug(String.format(MESSAGES.PERFORMING_REQUEST, request.getSystemId()));
}
setTimeout(connectionTimeoutInMillis, receiveTimeoutInMillis);
movilizerCloud.movilizerAsync(request, new AsyncHandlerAdapter<>(asyncHandler));
} catch (SOAPFaultException | HTTPException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getMessage());
}
throw new MovilizerWebServiceException(e);
} finally {
setTimeout(defaultConnectionTimeoutInMillis, defaultReceiveTimeoutInMillis);
}
}
示例8: setParticipantPassword
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
protected void setParticipantPassword(Long systemId, String systemPassword,
String deviceAddress, String newPassword,
PasswordHashTypes type) {
MovilizerResponse response;
try {
MovilizerParticipantConfiguration config = new MovilizerParticipantConfiguration();
config.setDeviceAddress(deviceAddress);
config.setPasswordHashType(type.getValue());
config.setPasswordHashValue(digestPassword(newPassword, type));
MovilizerRequest request = prepareUploadRequest(systemId, systemPassword,
new MovilizerRequest());
request.getParticipantConfiguration().add(config);
response = movilizerCloud.movilizer(request);
} catch (SOAPFaultException | HTTPException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getMessage());
}
throw new MovilizerWebServiceException(e);
}
if (logger.isInfoEnabled()) {
logger.info(String.format(MESSAGES.PASSWORD_SUCCESSFULY_CHANGED, deviceAddress,
response.getSystemId()));
}
}
示例9: doRoleCommand
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) {
URI uri = UriBuilder.fromUri(serverHostname)
.path("api")
.path(API_VERSION)
.path("clusters")
.path(clusterName)
.path("services")
.path(serviceName)
.path("roleCommands")
.path(roleCommand.toString())
.build();
String body = "{ \"items\": [ \"" + roleName + "\" ] }";
LOG.info("Executing POST against " + uri + " with body " + body + "...");
WebTarget webTarget = client.target(uri);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.post(Entity.json(body));
int statusCode = response.getStatus();
if (statusCode != Response.Status.OK.getStatusCode()) {
throw new HTTPException(statusCode);
}
}
示例10: httpPost
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private TestRailResponse httpPost(String path, String payload)
throws UnsupportedEncodingException, IOException, HTTPException {
TestRailResponse response;
do {
response = httpPostInt(path, payload);
if (response.getStatus() == 429) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
log(e.toString());
}
}
} while (response.getStatus() == 429);
return response;
}
示例11: httpPostInt
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private TestRailResponse httpPostInt(String path, String payload)
throws UnsupportedEncodingException, IOException, HTTPException {
TestRailResponse result;
PostMethod post = new PostMethod(host + "/" + path);
HttpClient httpclient = setUpHttpClient(post);
try {
StringRequestEntity requestEntity = new StringRequestEntity(
payload,
"application/json",
"UTF-8"
);
post.setRequestEntity(requestEntity);
Integer status = httpclient.executeMethod(post);
String body = new String(post.getResponseBody(), post.getResponseCharSet());
result = new TestRailResponse(status, body);
} finally {
post.releaseConnection();
}
return result;
}
示例12: downloadUrl
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
public static void downloadUrl(String url, File destFile) throws IOException, HTTPException {
File tmpFile = new File(destFile.getAbsoluteFile() + ".tmp");
Logger.getLogger(IOUtils.class).debug(String.format("Downloading URL %s to %s", url, tmpFile));
tmpFile.getParentFile().mkdirs();
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
int code = client.executeMethod(get);
if (code >= 200 && code < 300) {
copyToFileAndCloseStreams(get.getResponseBodyAsStream(), tmpFile);
tmpFile.renameTo(destFile);
}
else
Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url);
}
示例13: insertFaultMessage
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
final void insertFaultMessage(C context,
ProtocolException exception) {
if(exception instanceof HTTPException) {
context.put(MessageContext.HTTP_RESPONSE_CODE,((HTTPException)exception).getStatusCode());
}
if (context != null) {
// non-soap case
context.setPacketMessage(Messages.createEmpty(binding.getSOAPVersion()));
}
}
示例14: getResponse
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
@Override
protected Packet getResponse(Packet request, Exception e, WSDLPort port, WSBinding binding) {
Packet response = super.getResponse(request, e, port, binding);
if (e instanceof HTTPException) {
if (response.supports(MessageContext.HTTP_RESPONSE_CODE)) {
response.put(MessageContext.HTTP_RESPONSE_CODE, ((HTTPException)e).getStatusCode());
}
}
return response;
}
示例15: getJsonNodeFromURIGet
import javax.xml.ws.http.HTTPException; //导入依赖的package包/类
private JsonNode getJsonNodeFromURIGet(URI uri) throws IOException {
LOG.info("Executing GET against " + uri + "...");
ClientResponse response = client.resource(uri)
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
int statusCode = response.getStatus();
if (statusCode != Response.Status.OK.getStatusCode()) {
throw new HTTPException(statusCode);
}
// This API folds information as the value to an "items" attribute.
return new ObjectMapper().readTree(response.getEntity(String.class)).get("items");
}