当前位置: 首页>>代码示例>>Java>>正文


Java HttpURLConnection类代码示例

本文整理汇总了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"));
}
 
开发者ID:eclipse,项目名称:microprofile-jwt-auth,代码行数:19,代码来源:ProviderInjectionTest.java

示例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();
    }
}
 
开发者ID:fjoglar,项目名称:android-dev-challenge,代码行数:26,代码来源:NetworkUtils.java

示例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);
    }
}
 
开发者ID:UTN-FRBA-Mobile,项目名称:Clases-2017c1,代码行数:19,代码来源:UrlRequest.java

示例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);
    }
}
 
开发者ID:Microsoft,项目名称:azure-spring-boot,代码行数:18,代码来源:AzureADGraphClient.java

示例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();
}
 
开发者ID:Awesky,项目名称:awe-awesomesky,代码行数:17,代码来源:HttpUtil.java

示例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);
    }
  };
}
 
开发者ID:codahale,项目名称:passpol,代码行数:24,代码来源:BreachDatabase.java

示例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;
}
 
开发者ID:MobileDev418,项目名称:AndroidBackendlessChat,代码行数:12,代码来源:Response.java

示例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());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:CacheTest.java

示例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"));
}
 
开发者ID:eclipse,项目名称:microprofile-jwt-auth,代码行数:19,代码来源:RequiredClaimsTest.java

示例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();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:30,代码来源:HttpAdapter.java

示例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;
}
 
开发者ID:juebanlin,项目名称:util4j,代码行数:12,代码来源:HttpUtil.java

示例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);
        }
    }
}
 
开发者ID:1991wangliang,项目名称:pay,代码行数:15,代码来源:WebUtils.java

示例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();
    }
}
 
开发者ID:fjoglar,项目名称:android-dev-challenge,代码行数:27,代码来源:NetworkUtils.java

示例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);
}
 
开发者ID:shlee89,项目名称:athena,代码行数:24,代码来源:VirtualNetworkWebResourceTest.java

示例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;
  }
}
 
开发者ID:sinnerschrader,项目名称:SkillWill,代码行数:18,代码来源:SessionService.java


注:本文中的java.net.HttpURLConnection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。