下面列出了java.net.HttpURLConnection#HTTP_OK 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public int getContentLength(){
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = buildConnection();
httpURLConnection.connect();
int length = 0;
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
length = httpURLConnection.getContentLength();
}
return length;
} catch (Exception e) {
e.printStackTrace();
Log.e("Request Exception","the connection is timeout or maybe the server was closed.");
return 0;
}
}
public String getResponseString() throws Exception {
String response;
this.responseCode = conn.getResponseCode();
if (this.responseCode >= HttpURLConnection.HTTP_OK && this.responseCode <= 202) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
response = new String(byteData);
return response;
} else {
response = "RESPONSE-CODE :" + String.valueOf(this.responseCode);
}
return response;
}
/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public boolean finish(List<String> response) throws IOException {
response.clear();
//writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
return status == HttpURLConnection.HTTP_OK;
}
private int doDelete(String path, String event) {
List<AttributeSet> items = new ArrayList<>();
AttributeSet query = attributeExtractor.fromPath(path);
map.entrySet().stream()
.filter(entry -> entry.getKey().matches(query))
.forEach(entry -> items.add(entry.getKey()));
if (items.isEmpty()) return HttpURLConnection.HTTP_NOT_FOUND;
items.stream().forEach(item -> {
if (event != null && !event.isEmpty()) {
watchEventListeners.stream()
.filter(listener -> listener.attributeMatches(item))
.forEach(listener -> listener.sendWebSocketResponse(map.get(item), event));
map.remove(item);
}
});
return HttpURLConnection.HTTP_OK;
}
@Test
// This test purposefully causes an Exception by trying to parse results of a
// GetAuthorizationDetails API call with the RefundDetails parser.
// It's essentially just confirming we end up in the catch block.
// I'm adding this comment in case you turn on the special event handler
// for debugging purposes, and see strange FATAL_ERROR messages scrolling by:
// Setting special event handlerDefaultValidationEventHandler:
// [FATAL_ERROR]: unexpected element (uri:"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01", local:"GetAuthorizationDetailsResponse").
// Expected elements are <{http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01}GetRefundDetailsResponse>,
// <{http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01}GetRefundDetailsResult>,<{http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01}ResponseMetadata>
public void testJAXBExceptionResponse() throws Exception {
final String rawResponse = loadTestFile("GetAuthorizationDetailsResponse.xml");
final ResponseData response = new ResponseData(HttpURLConnection.HTTP_OK, rawResponse);
try {
final GetRefundDetailsResponseData res = Parser.getRefundDetailsData(response);
Assert.fail();
} catch (AmazonClientException e) {
Assert.assertEquals(e.getResponseXml(), rawResponse);
Assert.assertEquals(e.getStatusCode(), HttpURLConnection.HTTP_OK);
}
}
@POST
@Path("/deliverables/agency/{agencyNo}/type/{typeCode}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get list dataform by agencyNo and typeCode")
@ApiResponses(value = {
@ApiResponse (code = HttpURLConnection.HTTP_OK, message = "Return a list dataform"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not Found", response = ExceptionModel.class),
@ApiResponse (code = HttpURLConnection.HTTP_FORBIDDEN, message = "Accsess denied", response = ExceptionModel.class) })
public Response getDataFormByTypeCode (@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company,
@Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
@ApiParam(value = "id for agency", required = true) @PathParam("agencyNo") String agencyNo,
@ApiParam(value = "id for type", required = true) @PathParam("typeCode") String typeCode,
@FormParam("keyword") String keyword, @FormParam("start") String start, @FormParam("end") String end,
@FormParam("applicantIdNo") String applicantIdNo, @FormParam("deliverableState") String deliverableState);
@POST
@Path("/registrations/{id}/logs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "addRegistrationByRegistrationId)", response = RegistrationLogModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the RegistrationgModel was updated", response = RegistrationResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response addRegistrationByRegistrationId(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "id of registration", required = true) @PathParam("id") long id,
@ApiParam(value = "Metadata of RegistrationLog") @Multipart("author") String author,
@ApiParam(value = "Metadata of RegistrationLog") @Multipart("payload") String payload,
@ApiParam(value = "Metadata of RegistrationLog") @Multipart("content") String content);
@Override
protected InputStream getPartialResponse() throws IOException {
InputStream in = null;
int responseCode = getResponseCode();
if (responseCode == HttpURLConnection.HTTP_ACCEPTED
|| responseCode == HttpURLConnection.HTTP_OK) {
String head = httpResponse.headers().get(HttpHeaderHelper.CONTENT_LENGTH);
int cli = 0;
if (head != null) {
cli = Integer.parseInt(head);
}
head = httpResponse.headers().get(HttpHeaderHelper.TRANSFER_ENCODING);
boolean isChunked = head != null && HttpHeaderHelper.CHUNKED.equalsIgnoreCase(head);
head = httpResponse.headers().get(HttpHeaderHelper.CONNECTION);
boolean isEofTerminated = head != null && HttpHeaderHelper.CLOSE.equalsIgnoreCase(head);
if (cli > 0) {
in = getInputStream();
} else if (isChunked || isEofTerminated) {
// ensure chunked or EOF-terminated response is non-empty
try {
PushbackInputStream pin =
new PushbackInputStream(getInputStream());
int c = pin.read();
if (c != -1) {
pin.unread((byte)c);
in = pin;
}
} catch (IOException ioe) {
// ignore
}
}
}
return in;
}
/**
* Checks if is authenticated.
*
* @return null if authenticated.<br>
* a url to authenticate against if not authenticated.
* @throws Exception the exception
*/
public String isAuthenticated() throws Exception
{
String isAuthenticateUrl = buildUrl( "rest/is-authenticated" );
String ret;
ALMResponse response = httpGet( isAuthenticateUrl, null, null );
int responseCode = response.getStatusCode();
// if already authenticated
if ( responseCode == HttpURLConnection.HTTP_OK )
{
ret = null;
}
// if not authenticated - get the address where to authenticate
// via WWW-Authenticate
else if ( responseCode == HttpURLConnection.HTTP_UNAUTHORIZED )
{
Iterable<String> authenticationHeader = response.getResponseHeaders().get( "WWW-Authenticate" );
String newUrl = authenticationHeader.iterator().next().split( "=" )[1];
newUrl = newUrl.replace( "\"", "" );
newUrl += "/authenticate";
ret = newUrl;
}
// Not ok, not unauthorized. An error, such as 404, or 500
else
{
throw response.getFailure();
}
return ret;
}
/**
* @return Indicates if the remote service is available.
*/
public boolean isRemoteServiceAvailable() {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con =
(HttpURLConnection) new URL(conf.getConferenceServiceHost()).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
return false;
}
}
private void checkStatusCode(InputStream in, HttpClientTransport con) throws IOException {
int statusCode = con.statusCode;
String statusMessage = con.statusMessage;
// SOAP1.1 and SOAP1.2 differ here
if (binding instanceof SOAPBinding) {
if (binding.getSOAPVersion() == SOAPVersion.SOAP_12) {
//In SOAP 1.2, Fault messages can be sent with 4xx and 5xx error codes
if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || isErrorCode(statusCode)) {
// acceptable status codes for SOAP 1.2
if (isErrorCode(statusCode) && in == null) {
// No envelope for the error, so throw an exception with http error details
throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
}
return;
}
} else {
// SOAP 1.1
if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_ACCEPTED || statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
// acceptable status codes for SOAP 1.1
if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR && in == null) {
// No envelope for the error, so throw an exception with http error details
throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
}
return;
}
}
if (in != null) {
in.close();
}
throw new ClientTransportException(ClientMessages.localizableHTTP_STATUS_CODE(statusCode, statusMessage));
}
// Every status code is OK for XML/HTTP
}
@DELETE
@Path("/{id}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Remove a registrationTemplate by its id", response = RegistrationTemplatesModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier was removed", response = RegistrationTemplatesModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response removeRegistrationTemplate(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") long id);
@GET
@Path("/{referenceUid}/dossierAction/pedding")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "pending")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "pending"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossierPenddingByDossierId(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "dossier referenceUid", required = true) @PathParam("referenceUid") String referenceUid);
@Override
public Map<String, String> metadata(IRemoteSource source) throws NotConnectedException, PermissionException {
StringBuffer uriTmpl = (new StringBuffer()).append(restDataspaceUrl).append(source.getDataspace().value());
ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory)
.httpEngine(httpEngine)
.build();
ResteasyWebTarget target = client.target(uriTmpl.toString()).path(source.getPath());
Response response = null;
try {
response = target.request().header("sessionid", sessionId).head();
if (response.getStatus() != HttpURLConnection.HTTP_OK) {
if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new NotConnectedException("User not authenticated or session timeout.");
} else {
throw new RuntimeException(String.format("Cannot get metadata from %s in '%s' dataspace.",
source.getPath(),
source.getDataspace()));
}
}
MultivaluedMap<String, Object> headers = response.getHeaders();
Map<String, String> metaMap = Maps.newHashMap();
if (headers.containsKey(HttpHeaders.LAST_MODIFIED)) {
metaMap.put(HttpHeaders.LAST_MODIFIED, String.valueOf(headers.getFirst(HttpHeaders.LAST_MODIFIED)));
}
return metaMap;
} finally {
if (response != null) {
response.close();
}
}
}
@GET
@Path("/todo")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get a list of Dossiers", response = DossierResultsModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of Dossiers have been filtered", response = DossierResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossierProcessList(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @BeanParam DossierSearchModel query);
@GET
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get all registrationtemplates", response = RegistrationTemplatesResultsModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of all registrationtemplates", response = RegistrationTemplatesResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getRegistrationTemplates(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@QueryParam("formNo") String formNo,
@QueryParam("govAgencyCode") String govAgencyCode);
/**
* List of metacat view names.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @return List of metacat view names.
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mviews"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "List of metacat views",
notes = "List of metacat views for a catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The list of views is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
public List<NameDateDto> getMViews(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getMViews",
() -> this.mViewService.list(name)
);
}
@GET
@Path("/{id}/delegacy")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get a list delegacy users", response = ToUsers.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of assigned users have been filtered", response = DossierResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDelegacyUsers(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@PathParam("id") String id,
@Context ServiceContext serviceContext);
/**
* Read all contents of the given REST repository/subfolder and store them as {@link Document}s. If that fails, logs it.
* If the repository can not use the global search REST service,
* normal indexing ({@link #indexFolder(List, Folder, boolean, ProgressThread) indexFolder}) will be used!
*
* @param list
* the list to add the search documents to
* @param folder
* the subfolder which should be queried
* @param repository
* the repository to read all contents from
* @param fullIndex
* if {@code true}, RapidMiner AI Hub will be asked to create a full index result including metadata (slow); otherwise metadata is omitted
* @param pg
* the progress thread this is called from; needed if fall back to normal indexing
*/
private void indexRESTFolder(List<Document> list, Folder folder, RESTRepository repository, boolean fullIndex, ProgressThread pg) {
// relative path
String path = folder.getLocation().getPath();
if (path == null || Character.toString(RepositoryLocation.SEPARATOR).equals(path)) {
path = "";
}
try {
String apiPath = fullIndex ? API_REST_REMOTE_REPO_DETAILS : API_REST_REMOTE_REPO_SUMMARY;
String repoPrefix = repository.getPrefix();
if (repoPrefix != null && !repoPrefix.isEmpty()) {
repoPrefix = RepositoryLocation.SEPARATOR + repoPrefix;
}
HttpURLConnection conn = repository.getGlobalSearchConnection(apiPath, URLEncoder.encode(path, StandardCharsets.UTF_8.name()));
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/json");
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException(responseCode + " " + conn.getResponseMessage());
}
// query worked, parse JSON to items and add to search index
String json = Tools.readTextFile(conn.getInputStream());
RepositoryGlobalSearchItem[] repositorySearchItems = WebServiceTools.parseJsonString(json, RepositoryGlobalSearchItem[].class, false);
for (RepositoryGlobalSearchItem item : repositorySearchItems) {
// If an item has no parent, it's in the root folder.
// Because the name is locally defined, it is not known on RapidMiner AI Hub. Set it here.
if (item.getParent().isEmpty()) {
item.setParent(repository.getName());
}
String itemLocation = item.getLocation();
if (repoPrefix != null) {
if (!itemLocation.startsWith(repoPrefix)) {
// skip items that do not come from the correct prefix
continue;
}
// if there is a repo prefix, cut it from the actual location
itemLocation = itemLocation.substring(repoPrefix.length());
}
// for the same reason as above, always set the REST repository name as repository before the absolute location
item.setLocation(RepositoryLocation.REPOSITORY_PREFIX + repository.getName() + itemLocation);
list.add(createDocument(item));
}
} catch (IOException e) {
LogService.getRoot().log(Level.WARNING, "com.rapidminer.repository.global_search.RepositorySearchManager.error.initial_index_error_rest_folder", new Object[]{repository.getName() + path, e.getMessage()});
}
}
@Override
protected Boolean doInBackground(Void... voids) {
while (!isCancelled()) {
try {
Thread.sleep(1);
if (mWallpaper == null) return false;
if (mWallpaper.getDimensions() != null &&
mWallpaper.getMimeType() != null &&
mWallpaper.getSize() > 0) {
return false;
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
URL url = new URL(mWallpaper.getURL());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(15000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream stream = connection.getInputStream();
BitmapFactory.decodeStream(stream, null, options);
ImageSize imageSize = new ImageSize(options.outWidth, options.outHeight);
mWallpaper.setDimensions(imageSize);
mWallpaper.setMimeType(options.outMimeType);
int contentLength = connection.getContentLength();
if (contentLength > 0) {
mWallpaper.setSize(contentLength);
}
Database.get(mContext.get()).updateWallpaper(mWallpaper);
stream.close();
return true;
}
return false;
} catch (Exception e) {
LogUtil.e(Log.getStackTraceString(e));
return false;
}
}
return false;
}