Java Code Examples for java.net.HttpURLConnection

The following are top voted examples for showing how to use java.net.HttpURLConnection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   View source code 10 votes vote down vote up
@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"));
}
 
Example 2
Project: android-dev-challenge   File: NetworkUtils.java   View source code 9 votes vote down vote up
/**
 * 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();
    }
}
 
Example 3
Project: Clases-2017c1   File: UrlRequest.java   View source code 8 votes vote down vote up
@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);
    }
}
 
Example 4
Project: azure-spring-boot   File: AzureADGraphClient.java   View source code 8 votes vote down vote up
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);
    }
}
 
Example 5
Project: awe-awesomesky   File: HttpUtil.java   View source code 8 votes vote down vote up
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();
}
 
Example 6
Project: passpol   File: BreachDatabase.java   View source code 8 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 7
Project: AndroidBackendlessChat   File: Response.java   View source code 7 votes vote down vote up
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;
}
 
Example 8
Project: GitHub   File: CacheTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: microprofile-jwt-auth   File: RequiredClaimsTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 10
Project: OpenJSharp   File: HttpAdapter.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 11
Project: util4j   File: HttpUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: pay   File: WebUtils.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 13
Project: android-dev-challenge   File: NetworkUtils.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 14
Project: athena   File: VirtualNetworkWebResourceTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 15
Project: SkillWill   File: SessionService.java   View source code 6 votes vote down vote up
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;
  }
}
 
Example 16
Project: belling-spring-rabbitmq   File: HttpRequester.java   View source code 6 votes vote down vote up
/**
 * 得到响应对象
 * 
 * @param urlConnection
 * @return 响应对象
 * @throws IOException
 */
private HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
	HttpRespons httpResponser = new HttpRespons();
	try {
		InputStream in = urlConnection.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,
				Charset.forName(this.defaultContentEncoding)));
		httpResponser.contentCollection = new Vector<String>();
		StringBuffer temp = new StringBuffer();
		String line = bufferedReader.readLine();
		while (line != null) {
			httpResponser.contentCollection.add(line);
			temp.append(line).append("");
			line = bufferedReader.readLine();
		}
		bufferedReader.close();

		String ecod = urlConnection.getContentEncoding();
		if (ecod == null)
			ecod = this.defaultContentEncoding;

		httpResponser.urlString = urlString;

		httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
		httpResponser.file = urlConnection.getURL().getFile();
		httpResponser.host = urlConnection.getURL().getHost();
		httpResponser.path = urlConnection.getURL().getPath();
		httpResponser.port = urlConnection.getURL().getPort();
		httpResponser.protocol = urlConnection.getURL().getProtocol();
		httpResponser.query = urlConnection.getURL().getQuery();
		httpResponser.ref = urlConnection.getURL().getRef();
		httpResponser.userInfo = urlConnection.getURL().getUserInfo();

		httpResponser.content = temp.toString();
		httpResponser.contentEncoding = ecod;
		httpResponser.code = urlConnection.getResponseCode();
		httpResponser.message = urlConnection.getResponseMessage();
		httpResponser.contentType = urlConnection.getContentType();
		httpResponser.method = urlConnection.getRequestMethod();
		httpResponser.connectTimeout = urlConnection.getConnectTimeout();
		httpResponser.readTimeout = urlConnection.getReadTimeout();

		return httpResponser;
	} catch (IOException e) {
		throw e;
	} finally {
		if (urlConnection != null)
			urlConnection.disconnect();
	}
}
 
Example 17
Project: Android-Programming-BigNerd   File: FlickrFetchr.java   View source code 6 votes vote down vote up
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() + ": with " +
                    urlSpec);
        }
        
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 18
Project: shabdiz   File: URLUtils.java   View source code 6 votes vote down vote up
/**
 * Pings a given {@code url} for availability. Effectively sends a HEAD request and returns {@code true} if the response code is in
 * the {@code 200} - {@code 399} range.
 * @param url the url to be pinged.
 * @param timeout_millis the timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return {@code true} if the given {@code url} has returned response code within the range of {@code 200} - {@code 399} on a HEAD request, {@code false} otherwise
 */
public static boolean ping(final URL url, final int timeout_millis) {

    try {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(timeout_millis);
        connection.setReadTimeout(timeout_millis);
        connection.setRequestMethod(HEAD_REQUEST_METHOD);

        final int response_code = connection.getResponseCode();
        return HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_BAD_REQUEST;
    }
    catch (IOException exception) {
        return false;
    }
}
 
Example 19
Project: hadoop   File: TestRMFailover.java   View source code 6 votes vote down vote up
static String getRedirectURL(String url) {
  String redirectUrl = null;
  try {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    // do not automatically follow the redirection
    // otherwise we get too many redirections exception
    conn.setInstanceFollowRedirects(false);
    if(conn.getResponseCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT)
      redirectUrl = conn.getHeaderField("Location");
  } catch (Exception e) {
    // throw new RuntimeException(e);
  }
  return redirectUrl;
}
 
Example 20
Project: productai-java-sdk   File: RequestHelper.java   View source code 6 votes vote down vote up
public static <T extends BaseResponse> HttpResponse getResponse(BaseRequest<T> request) throws Exception {
    HttpResponse httpResponse;

    HttpURLConnection connection = createRequest(request);
    if (request.getRequestMethod() != HttpMethod.GET) {
        if (request.getQueryBytes() != null) {
            writeRequestParas(connection, request.getQueryBytes());
        } else {
            writeRequestParas(connection, request.getQueryString());
        }
    }
    int statusCode = connection.getResponseCode();

    byte[] bytes = readStreamBytes(connection);

    httpResponse = new HttpResponse();
    httpResponse.setStatusCode(statusCode);
    httpResponse.setResponseBytes(bytes);
    httpResponse.setHeaders(connection.getHeaderFields());

    return httpResponse;
}
 
Example 21
Project: pre-dem-android   File: HttpMonitorManager.java   View source code 6 votes vote down vote up
private boolean sendRequest(String url, String content) {
    LogUtils.d(TAG, "------url = " + url + "\ncontent = " + content);

    try {
        HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
                .setRequestMethod("POST")
                .setHeader("Content-Type", "application/x-gzip")
                .setHeader("Content-Encoding", "gzip")
                .setRequestBody(content)
                .setGzip(true)
                .build();

        int responseCode = httpConn.getResponseCode();
        boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
        return successful;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 22
Project: microprofile-jwt-auth   File: PrimitiveInjectionTest.java   View source code 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected groups claim is as expected")
public void verifyInjectedGroups() throws Exception {
    Reporter.log("Begin verifyInjectedGroups\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedGroups";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.groups.name(), new String[]{
                "Echoer", "Tester", "group1", "group2"})
            .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"));
}
 
Example 23
Project: opencps-v2   File: ServiceInfoManagement.java   View source code 6 votes vote down vote up
@GET
@Path("/{id}/filetemplates")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get FileTemplate list of ServiceInfo by its id)", response = FileTemplateResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the list of FileTemplate of ServiceInfo", response = FileTemplateResultsModel.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 getFileTemplatesOfServiceInfo(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext,
		@ApiParam(value = "id of ServiceInfo that need to be get the list of FileTemplates", required = true) @PathParam("id") String id);
 
Example 24
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection.java   View source code 6 votes vote down vote up
/**
 * <b>LISTSTATUS</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String listStatus(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    ensureValidToken();
    System.out.println("Token = "+token.isSet());

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?delegation="+delegation+"&op=LISTSTATUS",
                    URLUtil.encodePath(path))), token);
    conn.setRequestMethod("GET");
    conn.connect();
    String resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 25
Project: GitTalent   File: CouchbaseContainer.java   View source code 6 votes vote down vote up
public void callCouchbaseRestAPI(String url, String payload) throws IOException {
    String fullUrl = urlBase + url;
    HttpURLConnection httpConnection = (HttpURLConnection) ((new URL(fullUrl).openConnection()));
    httpConnection.setDoOutput(true);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8"));
    httpConnection.setRequestProperty("Authorization", "Basic " + encoded);
    DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
    out.writeBytes(payload);
    out.flush();
    out.close();
    httpConnection.getResponseCode();
    httpConnection.disconnect();
}
 
Example 26
Project: chromium-net-for-android   File: CronetBufferedOutputStreamTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithoutContentLengthOneMassiveWrite() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    OutputStream out = connection.getOutputStream();
    byte[] largeData = TestUtil.getLargeData();
    out.write(largeData);
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
Example 27
Project: cat-is-a-dog   File: DownloadImageTask.java   View source code 6 votes vote down vote up
/**
 * Download the image from the given URL
 * @param urlString the URL to download
 * @return a bitmap of the downloaded image
 */
private Bitmap downloadImage(String urlString) {
    Bitmap bmp = null;

    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        InputStream is = conn.getInputStream();
        bmp = BitmapFactory.decodeStream(is);
        if (bmp != null) {
            return bmp;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return bmp;
}
 
Example 28
Project: woodpecker   File: GetRequest.java   View source code 6 votes vote down vote up
public String performRequest(HttpURLConnection httpConnection) {
    try {
        httpConnection.setRequestMethod("GET");
        addHeaders(httpConnection);
        String response = readInputSteam(httpConnection.getInputStream());
        httpConnection.getInputStream().close();
        peck.getResponse().setRawResponse(response);
        peck.getResponse().setResponseCode(httpConnection.getResponseCode());
        peck.getResponse().setHeaders(httpConnection.getHeaderFields());
        return response;
    } catch (IOException e) {
        generateErrorResponse(peck.getResponse(), httpConnection);
        return null;
    } finally {
        httpConnection.disconnect();
    }
}
 
Example 29
Project: mockstar   File: MainPresenterImplTest.java   View source code 6 votes vote down vote up
@Test
public void testDemoResponseError503() {
    reset(mainSceneMock);
    MainPresenterImpl presenter = new MainPresenterImpl(schedulersProvider, pokeDataSource);

    MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_UNAVAILABLE);

    getErrorMockWebServer().enqueue(response);

    presenter.onSceneAdded(mainSceneMock, null);

    testScheduler.triggerActions();

    verify(mainSceneMock, times(0)).setApiText(anyString());
    verify(mainSceneMock, times(1)).showErrorDialog("Fire on the Server");
}
 
Example 30
Project: GitHub   File: ResponseCacheTest.java   View source code 6 votes vote down vote up
@Test public void varyMultipleFieldValuesWithMatch() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  URL url = server.url("/").url();
  HttpURLConnection multiConnection1 = openConnection(url);
  multiConnection1.setRequestProperty("Accept-Language", "fr-CA, fr-FR");
  multiConnection1.addRequestProperty("Accept-Language", "en-US");
  assertEquals("A", readAscii(multiConnection1));

  HttpURLConnection multiConnection2 = openConnection(url);
  multiConnection2.setRequestProperty("Accept-Language", "fr-CA, fr-FR");
  multiConnection2.addRequestProperty("Accept-Language", "en-US");
  assertEquals("A", readAscii(multiConnection2));
}
 
Example 31
Project: android-dev-challenge   File: NetworkUtils.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 32
Project: browser   File: HttpImageGetTask.java   View source code 6 votes vote down vote up
private Bitmap downloadUrl(String myurl) throws IOException {

		try {
			URL url = new URL(myurl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);
			return myBitmap;

		} catch (IOException e) {
			return null;
		}

	}
 
Example 33
Project: hadoop   File: HttpFSFileSystem.java   View source code 5 votes vote down vote up
/**
 * Set replication for an existing file.
 *
 * @param src file name
 * @param replication new replication
 *
 * @return true if successful;
 *         false if file does not exist or is a directory
 *
 * @throws IOException
 */
@Override
public boolean setReplication(Path src, short replication)
  throws IOException {
  Map<String, String> params = new HashMap<String, String>();
  params.put(OP_PARAM, Operation.SETREPLICATION.toString());
  params.put(REPLICATION_PARAM, Short.toString(replication));
  HttpURLConnection conn =
    getConnection(Operation.SETREPLICATION.getMethod(), params, src, true);
  HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_OK);
  JSONObject json = (JSONObject) HttpFSUtils.jsonParse(conn);
  return (Boolean) json.get(SET_REPLICATION_JSON);
}
 
Example 34
Project: bubichain-sdk-java   File: HttpKit.java   View source code 5 votes vote down vote up
/**
 *  鍙戦�丳ost璇锋眰
 * @param url 璇锋眰鍦板潃
 * @param params 璇锋眰鍙傛暟
 * @param https 鏄惁鍚姩https
 * @return
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	if(enableSSL){
		return post(url,params,true);
	}else{
		StringBuffer bufferRes = null;
     URL urlGet = new URL(url);
     HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
     // 杩炴帴瓒呮椂
     http.setConnectTimeout(50000);
     // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
     http.setReadTimeout(50000);
     http.setRequestMethod("POST");
     http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
     http.setDoOutput(true);
     http.setDoInput(true);
     http.connect();
	
     OutputStream out = http.getOutputStream();
     out.write(params.getBytes("UTF-8"));
     out.flush();
     out.close();
	
     InputStream in = http.getInputStream();
     BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
     String valueString = null;
     bufferRes = new StringBuffer();
     while ((valueString = read.readLine()) != null){
         bufferRes.append(valueString);
     }
     in.close();
     if (http != null) {
         // 鍏抽棴杩炴帴
         http.disconnect();
     }
     return bufferRes.toString();
	}
}
 
Example 35
Project: GitHub   File: JavaApiConverter.java   View source code 5 votes vote down vote up
/**
 * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to
 * supply the data. The URLConnection is assumed to already be connected. If this method returns
 * {@code null} the response is uncacheable.
 */
public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection)
    throws IOException {

  HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;

  Response.Builder okResponseBuilder = new Response.Builder();

  // Request: Create one from the URL connection.
  Headers responseHeaders = createHeaders(urlConnection.getHeaderFields());
  // Some request headers are needed for Vary caching.
  Headers varyHeaders = varyHeaders(urlConnection, responseHeaders);
  if (varyHeaders == null) {
    return null;
  }

  // OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
  String requestMethod = httpUrlConnection.getRequestMethod();
  RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod)
      ? Util.EMPTY_REQUEST
      : null;

  Request okRequest = new Request.Builder()
      .url(uri.toString())
      .method(requestMethod, placeholderBody)
      .headers(varyHeaders)
      .build();
  okResponseBuilder.request(okRequest);

  // Status line
  StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection));
  okResponseBuilder.protocol(statusLine.protocol);
  okResponseBuilder.code(statusLine.code);
  okResponseBuilder.message(statusLine.message);

  // A network response is required for the Cache to find any Vary headers it needs.
  Response networkResponse = okResponseBuilder.build();
  okResponseBuilder.networkResponse(networkResponse);

  // Response headers
  Headers okHeaders = extractOkResponseHeaders(httpUrlConnection, okResponseBuilder);
  okResponseBuilder.headers(okHeaders);

  // Response body
  ResponseBody okBody = createOkBody(urlConnection);
  okResponseBuilder.body(okBody);

  // Handle SSL handshake information as needed.
  if (httpUrlConnection instanceof HttpsURLConnection) {
    HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection;

    Certificate[] peerCertificates;
    try {
      peerCertificates = httpsUrlConnection.getServerCertificates();
    } catch (SSLPeerUnverifiedException e) {
      peerCertificates = null;
    }

    Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates();

    String cipherSuiteString = httpsUrlConnection.getCipherSuite();
    CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
    Handshake handshake = Handshake.get(TlsVersion.SSL_3_0, cipherSuite,
        nullSafeImmutableList(peerCertificates), nullSafeImmutableList(localCertificates));
    okResponseBuilder.handshake(handshake);
  }

  return okResponseBuilder.build();
}
 
Example 36
Project: uniquid-utils   File: RegistryDAOImpl.java   View source code 5 votes vote down vote up
@Override
public String retrieveProviderName(final String providerAddress) throws RegistryException {
	
	try {
		URL url = new URL(GET_URL.replace("%1&s", registryAddress));

		return HttpUtils.retrieveDataViaHttpGet(url, new ResponseDecoder<String>() {

			@Override
			public int getExpectedResponseCode() {
				return HttpURLConnection.HTTP_OK;
			}

			@Override
			public String manageResponse(String serverResponse) throws Exception {
				return addressFromJsonString(serverResponse, providerAddress);
			}

			@Override
			public String manageUnexpectedResponseCode(int responseCode, String responseMessage) throws Exception {
				if (HttpURLConnection.HTTP_NOT_FOUND == responseCode)
					return null;
				
				throw new RegistryException("Server returned " + responseCode + " " + responseMessage);
			}
		
		});
		
	} catch (Throwable t) {
		
		throw new RegistryException("Unexpected Exception", t);
		
	}
	
}
 
Example 37
Project: GroupDocs.Viewer-for-Java-App   File: Utils.java   View source code 5 votes vote down vote up
public static void downloadFile(String sourceURL,String fileNameWithPath) throws IOException{	
	final int BUFFER_SIZE = 4096;
	URL url = new URL(sourceURL);
	HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
	int responseCode = httpConn.getResponseCode();
	if (responseCode == HttpURLConnection.HTTP_OK) {
		String fileName = "";
		String disposition = httpConn.getHeaderField("Content-Disposition");
		String contentType = httpConn.getContentType();
		int contentLength = httpConn.getContentLength();

		if (disposition != null) {
			int index = disposition.indexOf("file=");
			if (index > 0)
				fileName = disposition.substring(index + 10,disposition.length() - 1);				
		} else {
			fileName = sourceURL.substring(sourceURL.lastIndexOf("/") + 1,sourceURL.length());
		}
		InputStream inputStream = httpConn.getInputStream();
		FileOutputStream outputStream = new FileOutputStream(fileNameWithPath);

		int bytesRead = -1;
		byte[] buffer = new byte[BUFFER_SIZE];
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		outputStream.close();
		inputStream.close();
	} 
	httpConn.disconnect();
}
 
Example 38
Project: Minecord   File: RequestUtils.java   View source code 5 votes vote down vote up
/**
 * Checks if a URL exists and can respond to an HTTP request.
 * @param url The URL to check.
 * @return True if the URL exists, false if it doesn't or an error occured.
 */
public static boolean checkURL(String url) {
	try {
		HttpURLConnection.setFollowRedirects(false);
		HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
		con.setRequestMethod("HEAD");
		return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
	} catch (Exception e) {
		return false;
	}
}
 
Example 39
Project: rapidminer   File: MarketplaceUpdateManager.java   View source code 5 votes vote down vote up
private InputStream openStream(URL url, ProgressListener listener, int minProgress, int maxProgress) throws IOException {
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    WebServiceTools.setURLConnectionDefaults(con);
    con.setDoInput(true);
    con.setDoOutput(false);
    String lengthStr = con.getHeaderField("Content-Length");

    InputStream urlIn;
    try {
        urlIn = con.getInputStream();
    } catch (IOException var11) {
        throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(), var11);
    }

    if(lengthStr != null && !lengthStr.isEmpty()) {
        try {
            long e = Long.parseLong(lengthStr);
            return new ProgressReportingInputStream(urlIn, listener, minProgress, maxProgress, e);
        } catch (NumberFormatException var10) {
            LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapid_i.deployment.update.client.UpdateManager.sending_illegal_content_length_error", new Object[]{lengthStr}), var10);
            return urlIn;
        }
    } else {
        LogService.getRoot().log(Level.WARNING, "com.rapid_i.deployment.update.client.UpdateManager.sending_content_length_error");
        return urlIn;
    }
}
 
Example 40
Project: civify-app   File: LoginAdapterImpl.java   View source code 5 votes vote down vote up
private LoginError generateException(int statusCode) {
    switch (statusCode) {
        case HttpURLConnection.HTTP_NOT_FOUND:
            return new LoginError(LoginError.ErrorType.USER_NOT_EXISTS,
                    USER_NOT_EXISTS_MESSAGE);
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            return new LoginError(LoginError.ErrorType.INVALID_CREDENTIALS,
                    INVALID_CREDENTIALS_MESSAGE);
        default:
            return null;
    }
}