本文整理汇总了Java中javax.net.ssl.HttpsURLConnection.getResponseCode方法的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection.getResponseCode方法的具体用法?Java HttpsURLConnection.getResponseCode怎么用?Java HttpsURLConnection.getResponseCode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.HttpsURLConnection
的用法示例。
在下文中一共展示了HttpsURLConnection.getResponseCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getContentOfRemoteFile
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Downloads the contents of a file from Redunda
*
* @param filename The name of the file to download
* @param trackFile If `true`, the file will be added to the list of tracked files
*
* @throws Throwable If an error occurs while downloading the file
*
* @return The content of the file or `null` if an error occurs. (for example status not 200)
* */
public String getContentOfRemoteFile(String filename, boolean trackFile) throws Throwable {
String encodedFilename;
try {
encodedFilename = URLEncoder.encode(this.encodeFilename(filename), "UTF-8");
} catch (Throwable e) {
e.printStackTrace();
return null;
}
String url = "https://redunda.sobotics.org/bots/data/"+encodedFilename+"?key="+this.apiKey;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", UserAgent.getUserAgent());
int responseCode = con.getResponseCode();
if (responseCode != 200)
return null;
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n"); //http://stackoverflow.com/a/4825297/4687348
}
in.close();
String responseString = response.toString();
//add to tracked files?
if (trackFile == true && this.trackedFiles.contains(filename))
this.trackedFiles.add(filename);
return responseString;
}
示例2: importToCloudCard
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String importToCloudCard(CardHolder cardHolder, Properties properties) {
try {
URL url = new URL(properties.getProperty(BASE_URL) + "/api/people");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
setConnectionHeaders(connection, properties);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(cardHolder.toJSON().getBytes());
outputStream.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
return "Failed : HTTP error code : " + connection.getResponseCode();
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return "Success";
}
示例3: getJSON
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* This function connects to the Loyalty API and returns a specific URL that matches best
* with the given store name.
*
* @param store The store name for which the logo has to be found
* @return The JSON-object as a String returned by the Loyalty-server. When something goes
* wrong during connection to the API, null is returned.
* @throws IOException Whenever something goes wrong while connecting with the remote API.
* @throws LogoNotFoundException When no logo is found for the given store or brand name.
*/
@Nullable
public String getJSON(String store) throws IOException, LogoNotFoundException {
store = URLEncoder.encode(store, "UTF-8");
String response;
URL url = new URL("https://www.abyx.be/loyalty/public/logo/" + URLEncoder.encode(store, "utf-8"));
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
InputStream in = new BufferedInputStream(connection.getInputStream());
response = IOUtils.toString(in, "UTF-8");
} else if (statusCode == 404) {
throw new LogoNotFoundException();
} else {
throw new IOException("Unable to connect to Loyalty API!");
}
return response;
}
示例4: execute
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private String execute(HttpsURLConnection connection) throws IOException {
int status = connection.getResponseCode();
if (status == HTTP_OK) {
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
connection.disconnect();
return response.toString();
} else {
if (status == HTTP_NO_CONTENT) {
throw new PublicAPIRequestRateLimitExceededException();
} else if (status == HTTP_FORBIDDEN) {
throw new ForbiddenException();
} else {
throw new RuntimeException();
}
}
}
开发者ID:B-V-R,项目名称:VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java,代码行数:24,代码来源:HttpClient.java
示例5: HttpResponse
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public HttpResponse(HttpsURLConnection httpsURLConnection) throws StarlingBankRequestException {
this.httpsURLConnection = httpsURLConnection;
try {
if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST){
this.is = httpsURLConnection.getInputStream();
}else {
this.is = httpsURLConnection.getErrorStream();
processStatusCode(httpsURLConnection);
}
this.statusCode = httpsURLConnection.getResponseCode();
this.expiration = httpsURLConnection.getExpiration();
this.request = httpsURLConnection.getURL();
this.expiration = httpsURLConnection.getExpiration();
this.lastModified = httpsURLConnection.getLastModified();
this.responseHeaders = httpsURLConnection.getHeaderFields();
this.contentType = httpsURLConnection.getContentType();
this.contentEncoding = httpsURLConnection.getContentEncoding();
} catch (IOException e) {
e.printStackTrace();
}
}
示例6: createTopicsIfNecessary
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public void createTopicsIfNecessary( String... topics ) throws Exception{
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
for( String topic : topics ){
URL messageHubUrl = new URL( getConfig(MessageHubConfig.MESSAGEHUB_REST_URL) + "/admin/topics" );
HttpsURLConnection con = (HttpsURLConnection) messageHubUrl.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("X-Auth-Token", getConfig(MessageHubConfig.MESSAGEHUB_API_KEY));
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write( "{\"name\":\"" + topic + "\"}" );
wr.flush();
int res = con.getResponseCode();
switch (res){
case 200:
case 202:
System.out.println("Successfully created topic: " + topic);
break;
case 422:
case 403:
System.out.println("Topic already exists in the server: " + topic);
break;
default:
throw new IllegalStateException("Error when trying to create topic: " + res + " Reason: " + con.getResponseMessage());
}
}
}
示例7: getRawAPIResponse
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String getRawAPIResponse(String urlSuffix, String requestMethod, String body) throws AuthorizationException, IOException, InsufficientValueException, CouldNotFindObjectException {
URL requestURL = new URL(LightrailConstants.API.apiBaseURL + urlSuffix);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) requestURL.openConnection();
httpsURLConnection.setRequestProperty(
LightrailConstants.API.AUTHORIZATION_HEADER_NAME,
LightrailConstants.API.AUTHORIZATION_TOKEN_TYPE + " " + Lightrail.apiKey);
httpsURLConnection.setRequestMethod(requestMethod);
if (body != null) {
httpsURLConnection.setRequestProperty(LightrailConstants.API.CONTENT_TYPE_HEADER_NAME, LightrailConstants.API.CONTENT_TYPE_JSON_UTF8);
httpsURLConnection.setDoOutput(true);
OutputStream wr = httpsURLConnection.getOutputStream();
wr.write(body.getBytes(StandardCharsets.UTF_8));
wr.flush();
wr.close();
}
int responseCode = httpsURLConnection.getResponseCode();
InputStream responseInputStream;
if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST) {
responseInputStream = httpsURLConnection.getInputStream();
} else {
responseInputStream = httpsURLConnection.getErrorStream();
}
BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseInputStream, StandardCharsets.UTF_8));
StringBuilder responseStringBuffer = new StringBuilder();
String inputLine;
while ((inputLine = responseReader.readLine()) != null)
responseStringBuffer.append(inputLine).append('\n');
responseReader.close();
String responseString = responseStringBuffer.toString();
if (responseCode > 204) {
handleErrors(responseCode, responseString);
}
return responseString;
}
示例8: getStreamsByGame
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Filter streams/channels by game and by language.
* Passes the JSON response to a Java object for easier use.
*
* @param game the game to get the channels for
* @param language filter all channels by language
* @return a list of the channels currently streaming for a given game + language
* @throws IOException
*/
public Set<String> getStreamsByGame(final String game, final String language) throws IOException {
/*
TODO: maybe handle the case for "all" languages
TODO: make this run in its own thread. See java.util.concurrency
TODO: organize the API better. This function is weak.
*/
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(STREAM_ENDPOINT)
.append(QUESTION_MARK)
.append(GAME_PARAM)
.append(EQUALS)
.append(game);
if (language != null) {
urlBuilder.append(AMPERSAND)
.append(LANG_PARAM)
.append(EQUALS)
.append(language);
}
String urlString = urlBuilder.toString();
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty(CLIENT_ID_HEADER, clientId);
if (con.getResponseCode() != Constants.RESPONSE_OK) {
throw new BadRequestException(BAD_CLIENT_ID + clientId);
}
channels = mapper.readValue(con.getInputStream(), ChannelContainer.class);
return channels.getChannels();
}
示例9: testHSTSRequestGet
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Test
public void testHSTSRequestGet() throws Exception {
String secureMe = "https://127.0.0.1:54322/secure-me";
URL url = new URL(secureMe);
HttpsURLConnection con = getUrlConnection(url);
int responseCode = con.getResponseCode();
assertEquals(404, responseCode);
assertEquals("max-age=604800", con.getHeaderField(StrictTransportHandler.HSTS_HEADER_NAME));
}
示例10: doExecute
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
final String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
if (StringUtils.isBlank(gRecaptchaResponse)) {
LOGGER.warn("Recaptcha response is missing from the request");
return getError(requestContext);
}
try {
final URL obj = new URL(recaptchaProperties.getVerifyUrl());
final HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", WebUtils.getHttpServletRequestUserAgent());
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
final String postParams = "secret=" + recaptchaProperties.getSecret() + "&response=" + gRecaptchaResponse;
LOGGER.debug("Sending 'POST' request to URL: [{}]", obj);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParams);
wr.flush();
}
final int responseCode = con.getResponseCode();
LOGGER.debug("Response Code: [{}]", responseCode);
if (responseCode == HttpStatus.OK.value()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
final String response = in.lines().collect(Collectors.joining());
LOGGER.debug("Google captcha response received: [{}]", response);
final JsonNode node = READER.readTree(response);
if (node.has("success") && node.get("success").booleanValue()) {
return null;
}
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return getError(requestContext);
}
示例11: verify
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Override
public void verify(String gRecaptchaResponse) throws RecaptchaException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
throw new RecaptchaException("Recapcha failed");
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
if (!jsonObject.getBoolean("success")) {
throw new RecaptchaException("Recapcha failed");
}
} catch (Exception e) {
throw new RecaptchaException("Recaptcha failed", e);
}
}
示例12: uploadAttachment
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private byte[] uploadAttachment(String method, String url, InputStream data,
long dataSize, byte[] key, ProgressListener listener)
throws IOException
{
URL uploadUrl = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
connection.setDoOutput(true);
if (dataSize > 0) {
connection.setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize));
} else {
connection.setChunkedStreamingMode(0);
}
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Connection", "close");
connection.connect();
try {
OutputStream stream = connection.getOutputStream();
AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream);
byte[] buffer = new byte[4096];
int read, written = 0;
while ((read = data.read(buffer)) != -1) {
out.write(buffer, 0, read);
written += read;
if (listener != null) {
listener.onAttachmentProgress(dataSize, written);
}
}
data.close();
out.flush();
out.close();
if (connection.getResponseCode() != 200) {
throw new IOException("Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
}
return out.getAttachmentDigest();
} finally {
connection.disconnect();
}
}
示例13: doInBackground
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Override
protected String doInBackground(String... params) {
String reqString = params[0];
String response = "";
try{
URL reqURL = new URL(reqString);
HttpsURLConnection conn = (HttpsURLConnection)reqURL.openConnection();
JSONObject tokenObject = new JSONObject();
byte[] requestBytes = null;
tokenObject.put("_token", mRequestor.getToken());
requestBytes = tokenObject.toString().getBytes();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(requestBytes);
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
}
catch (IOException|JSONException ex){
ex.printStackTrace();
}
return response;
}
示例14: verify
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static boolean verify(String gRecaptchaResponse){
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try{
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject object = (JSONObject)JSONValue.parse(new StringReader(response.toString()));
return (Boolean)object.get("success");
}catch(Exception e){
e.printStackTrace();
return false;
}
}
示例15: doInBackground
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* This is an asynchronously called function, that will send an HTTP POST request to the
* translator endpoint with the Korean text in the request.
* @return String response from the translator service.
*/
@Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL(TRANSLATE_API_ENDPOINT);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
// Set authorization header.
String authString = this.username + ":" + this.password;
byte[] base64Bytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
String base64String = new String(base64Bytes);
urlConnection.setRequestProperty("Authorization", "Basic " + base64String);
if (this.postData != null) {
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(postData.toString());
writer.flush();
writer.close();
}
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStreamReader streamReader = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
streamReader.close();
bufferedReader.close();
result = response.toString();
}
else {
System.out.println("Error translating. Response Code: " + statusCode);
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}