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   Source Code and License 11 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   Source Code and License 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   Source Code and License 9 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: Transwarp-Sample-Code   File: KerberosWebHDFSConnection.java   Source Code and License 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 24
Project: GitTalent   File: CouchbaseContainer.java   Source Code and License 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 25
Project: chromium-net-for-android   File: CronetBufferedOutputStreamTest.java   Source Code and License 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 26
Project: cat-is-a-dog   File: DownloadImageTask.java   Source Code and License 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 27
Project: woodpecker   File: GetRequest.java   Source Code and License 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 28
Project: mockstar   File: MainPresenterImplTest.java   Source Code and License 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 29
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 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 30
Project: android-dev-challenge   File: NetworkUtils.java   Source Code and License 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 31
Project: browser   File: HttpImageGetTask.java   Source Code and License 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 32
Project: hadoop   File: HttpFSFileSystem.java   Source Code and License 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 33
Project: bubichain-sdk-java   File: HttpKit.java   Source Code and License 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 34
Project: GitHub   File: JavaApiConverter.java   Source Code and License 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 35
Project: uniquid-utils   File: RegistryDAOImpl.java   Source Code and License 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 36
Project: GroupDocs.Viewer-for-Java-App   File: Utils.java   Source Code and License 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 37
Project: Minecord   File: RequestUtils.java   Source Code and License 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 38
Project: rapidminer   File: MarketplaceUpdateManager.java   Source Code and License 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 39
Project: alerta-fraude   File: CordovaResourceApi.java   Source Code and License 5 votes vote down vote up
public String getMimeType(Uri uri) {
    switch (getUriType(uri)) {
        case URI_TYPE_FILE:
        case URI_TYPE_ASSET:
            return getMimeTypeFromPath(uri.getPath());
        case URI_TYPE_CONTENT:
        case URI_TYPE_RESOURCE:
            return contentResolver.getType(uri);
        case URI_TYPE_DATA: {
            return getDataUriMimeType(uri);
        }
        case URI_TYPE_HTTP:
        case URI_TYPE_HTTPS: {
            try {
                HttpURLConnection conn = (HttpURLConnection)new URL(uri.toString()).openConnection();
                conn.setDoInput(false);
                conn.setRequestMethod("HEAD");
                String mimeType = conn.getHeaderField("Content-Type");
                if (mimeType != null) {
                    mimeType = mimeType.split(";")[0];
                }
                return mimeType;
            } catch (IOException e) {
            }
        }
    }
    
    return null;
}
 
Example 40
Project: chromium-net-for-android   File: CronetFixedModeOutputStreamTest.java   Source Code and License 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testFixedLengthStreamingModeLargeData() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    // largeData is 1.8 MB.
    byte[] largeData = TestUtil.getLargeData();
    connection.setFixedLengthStreamingMode(largeData.length);
    OutputStream out = connection.getOutputStream();
    int totalBytesWritten = 0;
    // Number of bytes to write each time. It is doubled each time
    // to make sure that the implementation can handle large writes.
    int bytesToWrite = 683;
    while (totalBytesWritten < largeData.length) {
        if (bytesToWrite > largeData.length - totalBytesWritten) {
            // Do not write out of bound.
            bytesToWrite = largeData.length - totalBytesWritten;
        }
        out.write(largeData, totalBytesWritten, bytesToWrite);
        totalBytesWritten += bytesToWrite;
        // About 5th iteration of this loop, bytesToWrite will be bigger than 16384.
        bytesToWrite *= 2;
    }
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
Example 41
Project: springboot-shiro-cas-mybatis   File: RestFulLogin.java   Source Code and License 5 votes vote down vote up
static URLConnection openConn(String urlk) throws MalformedURLException, IOException {  

      URL url = new URL(urlk);  
      HttpURLConnection hsu = (HttpURLConnection) url.openConnection();  
      hsu.setDoInput(true);  
      hsu.setDoOutput(true);  
      hsu.setRequestMethod("POST");  
      return hsu;  

  }
 
Example 42
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   Source Code and License 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testInputStreamReadLessBytesThanAvailable() throws Exception {
    String testInputString = "this is a really long header";
    byte[] testInputBytes = testInputString.getBytes();
    URL url = new URL(NativeTestServer.getEchoHeaderURL("foo"));
    HttpURLConnection urlConnection =
            (HttpURLConnection) url.openConnection();
    urlConnection.addRequestProperty("foo", testInputString);
    assertEquals(200, urlConnection.getResponseCode());
    assertEquals("OK", urlConnection.getResponseMessage());
    InputStream in = urlConnection.getInputStream();
    byte[] firstPart = new byte[testInputBytes.length - 10];
    int firstBytesRead = in.read(firstPart, 0, testInputBytes.length - 10);
    byte[] secondPart = new byte[10];
    int secondBytesRead = in.read(secondPart, 0, 10);
    assertEquals(testInputBytes.length - 10, firstBytesRead);
    assertEquals(10, secondBytesRead);
    for (int i = 0; i < firstPart.length; i++) {
        assertEquals(testInputBytes[i], firstPart[i]);
    }
    for (int i = 0; i < secondPart.length; i++) {
        assertEquals(testInputBytes[firstPart.length + i], secondPart[i]);
    }
    urlConnection.disconnect();
}
 
Example 43
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
private void assertGatewayTimeout(HttpURLConnection connection) throws IOException {
  try {
    connection.getInputStream();
    fail();
  } catch (FileNotFoundException expected) {
  }
  assertEquals(504, connection.getResponseCode());
  assertEquals(-1, connection.getErrorStream().read());
}
 
Example 44
Project: GitHub   File: UrlConnectionCacheTest.java   Source Code and License 5 votes vote down vote up
/**
 * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal
 * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and
 * HttpURLConnection was always HTTP; in practice redirects mean that each can do either.
 *
 * https://github.com/square/okhttp/issues/214
 */
@Test public void secureResponseCachingAndProtocolRedirects() throws IOException {
  server2.useHttps(sslClient.socketFactory, false);
  server2.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setBody("ABC"));
  server2.enqueue(new MockResponse().setBody("DEF"));

  server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
      .addHeader("Location: " + server2.url("/").url()));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
      .build());

  HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
  assertEquals("ABC", readAscii(connection1));

  // Cached!
  HttpURLConnection connection2 = urlFactory.open(server.url("/").url());
  assertEquals("ABC", readAscii(connection2));

  assertEquals(4, cache.requestCount()); // 2 direct + 2 redirect = 4
  assertEquals(2, cache.hitCount());
}
 
Example 45
Project: redirector   File: ReportManager.java   Source Code and License 5 votes vote down vote up
public void clearSessionLog() {
    Response response = serviceHelper.getRequestBuilder(END_TO_END_REPORT_ENDPOINT, MediaType.APPLICATION_JSON).delete();
    if (response.getStatus() == HttpURLConnection.HTTP_OK) {
        log.info("Session log has been cleared successfully");
    } else {
        log.error("Session log has not been cleared");
    }
}
 
Example 46
Project: boohee_v5.6   File: HurlStack.java   Source Code and License 5 votes vote down vote up
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}
 
Example 47
Project: Learning-Spring-Boot-2.0-Second-Edition   File: LearningSpringBootHealthIndicator.java   Source Code and License 5 votes vote down vote up
@Override
public Health health() {
	try {
		URL url =
			new URL("http://greglturnquist.com/learning-spring-boot");
		HttpURLConnection conn =
			(HttpURLConnection) url.openConnection();
		int statusCode = conn.getResponseCode();
		if (statusCode >= 200 && statusCode < 300) {
			return Health.up().build();
		} else {
			return Health.down()
				.withDetail("HTTP Status Code", statusCode)
				.build();
		}
	} catch (IOException e) {
		return Health.down(e).build();
	}
}
 
Example 48
Project: Wurst-MC-1.12   File: MiscUtils.java   Source Code and License 5 votes vote down vote up
public static String post(URL url, String content, String contentType)
	throws IOException
{
	
	HttpURLConnection connection =
		(HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
	connection.setRequestMethod("POST");
	connection.setRequestProperty("Content-Type", contentType);
	connection.setRequestProperty("Content-Length",
		"" + content.getBytes().length);
	connection.setRequestProperty("Content-Language", "en-US");
	connection.setUseCaches(false);
	connection.setDoInput(true);
	connection.setDoOutput(true);
	DataOutputStream output =
		new DataOutputStream(connection.getOutputStream());
	output.writeBytes(content);
	output.flush();
	output.close();
	
	BufferedReader input = new BufferedReader(
		new InputStreamReader(connection.getInputStream()));
	StringBuffer buffer = new StringBuffer();
	for(String line; (line = input.readLine()) != null;)
	{
		buffer.append(line);
		buffer.append("\n");
	}
	input.close();
	return buffer.toString();
}
 
Example 49
Project: SWGEmuServerStatus   File: DownloadUrlTask.java   Source Code and License 5 votes vote down vote up
private InputStream downloadUrl(final String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}
 
Example 50
Project: cloud-c4c-ticket-duplicate-finder-ext   File: HTTPConnector.java   Source Code and License 5 votes vote down vote up
public SimpleHttpResponse executeGET(String path) throws InvalidResponseException, IOException {
	DestinationConfiguration destinationConfiguration = lookupDestinationConfiguration();
	URL requestURL = getRequestURL(destinationConfiguration, path);
	LOGGER.info(INFO_REQUEST_METHOD, requestURL.toString());
	HttpURLConnection urlConnection = openConnection(destinationConfiguration, requestURL);
	return executeMethodGET(urlConnection);
}
 
Example 51
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
/** @return the request with the conditional get headers. */
private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception {
  // scenario 1: condition succeeds
  server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK"));
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  // scenario 2: condition fails
  server.enqueue(response.setBody("B").setStatus("HTTP/1.1 200 B-OK"));
  server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 C-OK").setBody("C"));

  URL valid = server.url("/valid").url();
  HttpURLConnection connection1 = openConnection(valid);
  assertEquals("A", readAscii(connection1));
  assertEquals(HttpURLConnection.HTTP_OK, connection1.getResponseCode());
  assertEquals("A-OK", connection1.getResponseMessage());
  HttpURLConnection connection2 = openConnection(valid);
  assertEquals("A", readAscii(connection2));
  assertEquals(HttpURLConnection.HTTP_OK, connection2.getResponseCode());
  assertEquals("A-OK", connection2.getResponseMessage());

  URL invalid = server.url("/invalid").url();
  HttpURLConnection connection3 = openConnection(invalid);
  assertEquals("B", readAscii(connection3));
  assertEquals(HttpURLConnection.HTTP_OK, connection3.getResponseCode());
  assertEquals("B-OK", connection3.getResponseMessage());
  HttpURLConnection connection4 = openConnection(invalid);
  assertEquals("C", readAscii(connection4));
  assertEquals(HttpURLConnection.HTTP_OK, connection4.getResponseCode());
  assertEquals("C-OK", connection4.getResponseMessage());

  server.takeRequest(); // regular get
  return server.takeRequest(); // conditional get
}
 
Example 52
Project: app_secompufscar   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
public static String getResponseFromHttpUrl(URL url, Context context) throws IOException {
    if (updateConnectionState(context)) {

        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;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            urlConnection.disconnect();
        }
    } else {
        return null;
    }
}
 
Example 53
Project: pac4j-plus   File: CommonHelper.java   Source Code and License 5 votes vote down vote up
private static InputStream getInputStreamViaHttp(String name) {
    URLConnection con = null;
    try {
        URL url = new URL(name);
        con = url.openConnection();
        return con.getInputStream();
    } catch (IOException ex) {
        // Close the HTTP connection (if applicable).
        if (con instanceof HttpURLConnection) {
            ((HttpURLConnection) con).disconnect();
        }
        throw new TechnicalException(ex);
    }
}
 
Example 54
Project: Auto.js   File: DownloadTask.java   Source Code and License 5 votes vote down vote up
@Override
public Boolean call() throws IOException {
    try (AutoHttpURLConnection connection = new AutoHttpURLConnection(mUrl)) {
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }
        int total = connection.getContentLength();
        InputStream input = connection.getInputStream();
        FileOutputStream output = new FileOutputStream(mPath);
        return download(input, output, total);
    } catch (Exception e) {
        throw e;
    }
}
 
Example 55
Project: comdor   File: FollowUserTestCase.java   Source Code and License 5 votes vote down vote up
/**
 * Follow can follow the commander.
 * @throws Exception If something goes wrong.
 */
@Test
public void fullowsUserSuccessfuly() throws Exception {
    int port = this.port();
    final MkContainer github = new MkGrizzlyContainer().next(
        new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT)
    ).start(port);

    final Command com = this.mockMention();
    Mockito.when(com.issue().repo().github().entry())
        .thenReturn(new ApacheRequest("http://localhost:" + port + "/"));
    
    final Log log = Mockito.mock(Log.class);
    final Logger slf4j = Mockito.mock(Logger.class);
    Mockito.when(log.logger()).thenReturn(slf4j);
    
    try {
        new FollowUser(new Step.Fake(true)).perform(com, log);
        
        Mockito.verify(slf4j).info(
            "Following Github user " + com.author() + " ..."
        );
        Mockito.verify(slf4j).info("Followed user " + com.author() + " .");
        final MkQuery request = github.take();
        MatcherAssert.assertThat(
            request.uri().toString(),
                Matchers.equalTo("/user/following/" + com.author())
        );
        MatcherAssert.assertThat(request.method(), Matchers.equalTo("PUT"));
    } finally {
        github.stop();
    }
}
 
Example 56
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   Source Code and License 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testInputStreamReadOneByte() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // Make the server echo a large request body, so it exceeds the internal
    // read buffer.
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    byte[] largeData = TestUtil.getLargeData();
    connection.setFixedLengthStreamingMode(largeData.length);
    connection.getOutputStream().write(largeData);
    InputStream in = connection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int b;
    while ((b = in.read()) != -1) {
        out.write(b);
    }

    // All data has been read. Try reading beyond what is available should give -1.
    assertEquals(-1, in.read());
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    String responseData = new String(out.toByteArray());
    TestUtil.checkLargeData(responseData);
}
 
Example 57
Project: ViperBot   File: ResponseUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Throws the appropriate ClarifaiException for the response code from an HttpURLConnection,
 * populating the message from the response payload.
 */
static void throwExceptionForErrorResponse(HttpURLConnection conn, BaseResponse response)
    throws IOException, ClarifaiException {
  String errorMessage = "";
  if (response.statusCode != null) {
    errorMessage += response.statusCode;
  }
  if (response.statusMsg != null) {
    errorMessage += " " + response.statusMsg;
  }
  if (response.results != null && response.results.isJsonPrimitive()) {
    errorMessage += " " + response.results.getAsString();
  }
  if (errorMessage.length() == 0) {
    errorMessage = conn.getResponseMessage();
  }

  int code = conn.getResponseCode();
  if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
    throw new ClarifaiNotAuthorizedException(errorMessage);
  } else if (code == 429) {  // Too Many Requests
    int waitSeconds = conn.getHeaderFieldInt("X-Throttle-Wait-Seconds", 10);
    throw new ClarifaiThrottledException(errorMessage, waitSeconds);
  } else if (code >= 400 && code < 500) {
    throw new ClarifaiBadRequestException(errorMessage);
  } else if (code >= 500 && code < 600) {
    throw new ClarifaiException(errorMessage);
  } else {
    throw new ClarifaiException("Unexpected HTTP status code (" + code + "): " + errorMessage);
  }
}
 
Example 58
Project: android-tv-news   File: RSSReader.java   Source Code and License 5 votes vote down vote up
/**
 * Send HTTP GET request and parse the XML response to construct an in-memory
 * representation of an RSS 2.0 feed.
 *
 * @param uri RSS 2.0 feed URI
 * @return in-memory representation of downloaded RSS feed
 * @throws RSSReaderException if RSS feed could not be retrieved because of
 *           HTTP error
 * @throws RSSFault if an unrecoverable IO error has occurred
 */
public RSSFeed load(String uri) throws RSSReaderException {
    InputStream feedStream = null;
    try {
        URL url = new URL(uri);
        // Send GET request to URI
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.connect();

        // Check if server response is valid
        if (conn.getResponseCode() != 200) {
            throw new RSSReaderException(conn.getResponseCode(),
                    conn.getResponseMessage());
        }

        // Extract content stream from HTTP response
        feedStream = conn.getInputStream();
        RSSFeed feed = parser.parse(feedStream);

        if (feed.getLink() == null) {
            feed.setLink(android.net.Uri.parse(uri));
        }

        return feed;
    } catch (IOException e) {
        throw new RSSFault(e);
    } finally {
        Resources.closeQuietly(feedStream);
    }
}
 
Example 59
Project: LiteJavaWebsite   File: NanoWebsiteTests.java   Source Code and License 5 votes vote down vote up
private String loadContentFromUrl(String url) {
    try {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("GET");
        return new InputStreamToString(con.getInputStream()).get();
    } catch(Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 60
Project: opencps-v2   File: ServiceInfoManagement.java   Source Code and License 5 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);