Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

In this page you can find the example usage for java.net URL openConnection.

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:com.infosupport.service.LPRServiceCaller.java

public static JSONObject doGet(String urlString) {
    String json = null;/*  ww  w  .  j a  va2s .co m*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        while ((output = br.readLine()) != null) {
            json = output;
            System.out.println(json + "from doGet");
        }
        conn.disconnect();
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(TAG, "Kon geen JsonObject maken van het response");
    }
    return jsonObject;
}

From source file:com.leosys.core.utils.HttpServiceImpl.java

public static String getMyitem(String letter, Integer page) {
    Properties p = new Properties();
    String urls = getXmlPath();//from ww w  .  j  ava  2  s  .  c o m
    try {
        p.load(new FileInputStream(urls));
    } catch (Exception e) {
        e.printStackTrace();
    }
    String subUrl = p.getProperty("path");
    String restUrl = subUrl + "model=myservice&action=getwebdomainsitebypage&page=" + page + "&pagesize=10";
    if (StringUtils.isNotEmpty(letter)) {
        restUrl += "&letter=" + letter;
    }
    StringBuffer strBuf;
    strBuf = new StringBuffer();

    try {
        URL url = new URL(restUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));//?  
        String line = null;
        while ((line = reader.readLine()) != null)
            strBuf.append(line + " ");
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(strBuf.toString());
    return strBuf.toString();
}

From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username,
            password);//from www .  ja  va 2  s .  c o m

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();
}

From source file:com.telefonica.iot.perseo.test.Help.java

public static Res doMethod(String url, String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);//ww  w .ja v  a  2  s .c  om
    int responseCode = con.getResponseCode();
    String body = getBodyResponse(con);
    return new Res(responseCode, body);
}

From source file:com.pentaho.ctools.utils.HttpUtils.java

/**
 * This method shall return the status of HTTP request.
 *
 * @param url//w w  w . j  a v  a 2  s  .  co  m
 * @return
 * @throws Exception
 */
public static int GetHttpStatus(String url) {
    LOG.debug("The URL: " + url);
    int nHttpStatus = HttpStatus.SC_BAD_REQUEST;

    try {
        URL oUrl = new URL(url);
        URLConnection uc = oUrl.openConnection();
        uc.connect();
        nHttpStatus = ((HttpURLConnection) uc).getResponseCode();
        LOG.debug("HTTP Status:" + nHttpStatus);
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
    }

    return nHttpStatus;
}

From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {/*from   w  w  w . j av  a  2  s .c  o  m*/
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.intellectualcrafters.plot.uuid.UUIDFetcher.java

private static HttpURLConnection createConnection() throws Exception {
    final URL url = new URL(PROFILE_URL);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);//from   ww w  .jav a 2s  . co  m
    connection.setDoInput(true);
    connection.setDoOutput(true);
    return connection;
}

From source file:Main.java

public static void connectAndSendHttp(ByteArrayOutputStream baos) {
    try {//from  w  w w.  j  a  v a2 s  .  c  o  m

        URL url;
        url = new URL("http://10.0.2.2:8080");

        String charset = "UTF-8";

        HttpURLConnection conn;

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = conn.getOutputStream();
        output.write(baos.toByteArray());
        output.close();
        conn.getInputStream();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendGet(String urlString, String apiKey) {

    try {/*w w w.ja  v a 2  s  .co  m*/

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.telefonica.iot.perseo.test.Help.java

public static Res sendMethod(String url, String body, String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);//from  w  ww.j  a  va 2 s  .co m
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    String responseBody = getBodyResponse(con);
    return new Res(responseCode, responseBody);
}