本文整理汇总了Java中java.net.HttpURLConnection类的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection类的具体用法?Java HttpURLConnection怎么用?Java HttpURLConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpURLConnection类属于java.net包,在下文中一共展示了HttpURLConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: verifyInjectedJTI2
import java.net.HttpURLConnection; //导入依赖的package包/类
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
description = "Verify that the injected jti claim is as expected")
public void verifyInjectedJTI2() throws Exception {
Reporter.log("Begin verifyInjectedJTI\n");
String uri = baseURL.toExternalForm() + "/endp/verifyInjectedJTI";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.jti.name(), "a-123")
.queryParam(Claims.auth_time.name(), authTimeClaim);
Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
String replyString = response.readEntity(String.class);
JsonReader jsonReader = Json.createReader(new StringReader(replyString));
JsonObject reply = jsonReader.readObject();
Reporter.log(reply.toString());
Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
示例2: getResponseFromHttpUrl
import java.net.HttpURLConnection; //导入依赖的package包/类
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
示例3: run
import java.net.HttpURLConnection; //导入依赖的package包/类
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
int responseCode = connection.getResponseCode();
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.read(buffer)) > 0) {
responseBody.write(buffer, 0, bytesRead);
}
listener.onReceivedBody(responseCode, responseBody.toByteArray());
}
catch (Exception e) {
listener.onError(e);
}
}
示例4: getUserMembershipsV1
import java.net.HttpURLConnection; //导入依赖的package包/类
public static String getUserMembershipsV1(String accessToken) throws Exception {
final String userMembershipRestAPIv1 = "https://graph.windows.net/me/memberOf?api-version=1.6";
final URL url = new URL(userMembershipRestAPIv1);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty("Authorization", accessToken);
conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new Exception(responseInJson);
}
}
示例5: doGet
import java.net.HttpURLConnection; //导入依赖的package包/类
public void doGet(String url) throws Exception{
URL localURL = new URL(url);
URLConnection con = openConnection(localURL);
HttpURLConnection httpCon = (HttpURLConnection)con;
httpCon.setRequestProperty("Accept-Charset",CHARSET);
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if(httpCon.getResponseCode()>=300){
throw new RuntimeException("请求失败...");
}
InputStreamReader isr = new InputStreamReader(httpCon.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String res = reader.readLine();
System.out.println(res);
isr.close();
reader.close();
}
示例6: haveIBeenPwned
import java.net.HttpURLConnection; //导入依赖的package包/类
/**
* A client for <a href="https://haveibeenpwned.com/">Have I Been Pwned</a>'s online password
* checking. Passwords are hashed with SHA-1 before being sent.
*
* @return an online database of breached passwords
*/
static BreachDatabase haveIBeenPwned() {
return password -> {
try {
final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
final byte[] hash = sha1.digest(PasswordPolicy.normalize(password));
final StringBuilder s =
new StringBuilder("https://haveibeenpwned.com/api/v2/pwnedpassword/");
for (byte b : hash) {
s.append(String.format("%02x", b));
}
final HttpURLConnection conn = (HttpURLConnection) new URL(s.toString()).openConnection();
return conn.getResponseCode() == 200;
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
};
}
示例7: createResponsesFromString
import java.net.HttpURLConnection; //导入依赖的package包/类
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
JSONTokener tokener = new JSONTokener(responseString);
Object resultObject = tokener.nextValue();
List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n",
requests.getId(), responseString.length(), responses);
return responses;
}
示例8: networkInterceptorInvokedForConditionalGet
import java.net.HttpURLConnection; //导入依赖的package包/类
@Test public void networkInterceptorInvokedForConditionalGet() throws Exception {
server.enqueue(new MockResponse()
.addHeader("ETag: v1")
.setBody("A"));
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
// Seed the cache.
HttpUrl url = server.url("/");
assertEquals("A", get(url).body().string());
final AtomicReference<String> ifNoneMatch = new AtomicReference<>();
client = client.newBuilder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
return chain.proceed(chain.request());
}
}).build();
// Confirm the value is cached and intercepted.
assertEquals("A", get(url).body().string());
assertEquals("v1", ifNoneMatch.get());
}
示例9: verifyIssuerClaim
import java.net.HttpURLConnection; //导入依赖的package包/类
@RunAsClient
@Test(groups = TEST_GROUP_JWT,
description = "Verify that the token issuer claim is as expected")
public void verifyIssuerClaim() throws Exception {
Reporter.log("Begin verifyIssuerClaim");
String uri = baseURL.toExternalForm() + "/endp/verifyIssuer";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.iss.name(), TEST_ISSUER)
.queryParam(Claims.auth_time.name(), authTimeClaim);
Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
String replyString = response.readEntity(String.class);
JsonReader jsonReader = Json.createReader(new StringReader(replyString));
JsonObject reply = jsonReader.readObject();
Reporter.log(reply.toString());
Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
示例10: publishWSDL
import java.net.HttpURLConnection; //导入依赖的package包/类
/**
* Sends out the WSDL (and other referenced documents)
* in response to the GET requests to URLs like "?wsdl" or "?xsd=2".
*
* @param con
* The connection to which the data will be sent.
*
* @throws java.io.IOException when I/O errors happen
*/
public void publishWSDL(@NotNull WSHTTPConnection con) throws IOException {
con.getInput().close();
SDDocument doc = wsdls.get(con.getQueryString());
if (doc == null) {
writeNotFoundErrorPage(con,"Invalid Request");
return;
}
con.setStatus(HttpURLConnection.HTTP_OK);
con.setContentTypeResponseHeader("text/xml;charset=utf-8");
OutputStream os = con.getProtocol().contains("1.1") ? con.getOutput() : new Http10OutputStream(con);
PortAddressResolver portAddressResolver = getPortAddressResolver(con.getBaseAddress());
DocumentAddressResolver resolver = getDocumentAddressResolver(portAddressResolver);
doc.writeTo(portAddressResolver, resolver, os);
os.close();
}
示例11: buildSSLConn
import java.net.HttpURLConnection; //导入依赖的package包/类
public HttpURLConnection buildSSLConn(String url)throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setConnectTimeout(connectTimeOut);
conn.setReadTimeout(readTimeOut);
return conn;
}
示例12: getResponseAsString
import java.net.HttpURLConnection; //导入依赖的package包/类
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
示例13: getResponseFromHttpUrl
import java.net.HttpURLConnection; //导入依赖的package包/类
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response, null if no response
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
示例14: testPostVirtualNetwork
import java.net.HttpURLConnection; //导入依赖的package包/类
/**
* Tests adding of new virtual network using POST via JSON stream.
*/
@Test
public void testPostVirtualNetwork() {
expect(mockVnetAdminService.createVirtualNetwork(tenantId2)).andReturn(vnet1);
expectLastCall();
replay(mockVnetAdminService);
WebTarget wt = target();
InputStream jsonStream = TenantWebResourceTest.class
.getResourceAsStream("post-tenant.json");
Response response = wt.path("vnets").request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertThat(location, Matchers.startsWith("/vnets/" + vnet1.id().toString()));
verify(mockVnetAdminService);
}
示例15: isTokenInProxy
import java.net.HttpURLConnection; //导入依赖的package包/类
private boolean isTokenInProxy(String token) {
try {
URL authUrl = new URL(oAuthUrl);
HttpURLConnection connection = (HttpURLConnection) authUrl.openConnection();
connection.addRequestProperty("Cookie", "_oauth2_proxy=" + token);
connection.connect();
int resonseCode = connection.getResponseCode();
connection.disconnect();
logger.debug("Successfully checked token with oauth proxy, result {}", resonseCode);
return resonseCode == HttpStatus.ACCEPTED.value();
} catch (IOException e) {
logger.error("Failed to check session token at oauth Proxy");
return false;
}
}