Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

static String getUserInfo(String server_url, String access_token) {
    // android.os.Debug.waitForDebugger();

    Log.d(TAG, "getUserInfo server_url=" + server_url);
    Log.d(TAG, "getUserInfo access_token=" + access_token);

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(access_token)) {
        return null;
    }/* ww  w.  j  a v  a2s.c  o m*/

    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    Logd(TAG, "getUserInfo : " + userinfo_endpoint);
    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint + "?access_token=" + access_token);
    huc.setInstanceFollowRedirects(false);
    // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + access_token);

    // default result
    String result = null;

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Logd(TAG, "getUserInfo failed");
        e.printStackTrace();
    }

    return result;
}

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password./*from www .  ja va  2s  .  co m*/
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @param connection/*  w  w w  . j ava2 s.c  o m*/
 *             the HttpURLConnection of web server page.
 * @throws IOException
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse readPage(HttpURLConnection connection) throws IOException {
    connection.connect();
    int responseCode = connection.getResponseCode();
    String lLine = null;

    String responseMessage = "";
    try {
        BufferedReader messageReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder messageBuilder = new StringBuilder();
        while ((lLine = messageReader.readLine()) != null) {
            messageBuilder.append(lLine);
            messageBuilder.append('\n');
        }
        messageReader.close();
        responseMessage = messageBuilder.toString();
    } catch (Exception e) {
        responseMessage = "";
    }

    String errorMessage = "";
    try {
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        StringBuilder errorBuilder = new StringBuilder();
        while ((lLine = errorReader.readLine()) != null) {
            errorBuilder.append(lLine);
            errorBuilder.append('\n');
        }
        errorReader.close();
        errorMessage = errorBuilder.toString();
    } catch (Exception e) {
        errorMessage = "";
    }

    connection.disconnect();
    return new HTTPResponse(responseCode, responseMessage, errorMessage);
}

From source file:dk.cafeanalog.AnalogDownloader.java

private ArrayList<Opening> getOpenings() throws IOException, JSONException, ParseException {
    if (System.currentTimeMillis() - mLastGet < TIME_BETWEEN_DOWNLOADS && mOpeningsCache != null) {
        return mOpeningsCache;
    }//  www .  j  a  va 2 s . c o m
    mLastGet = System.currentTimeMillis();
    URL url = new URL("http", "cafeanalog.dk", "api/shifts");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("GET");
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String s;
    while ((s = reader.readLine()) != null) {
        builder.append(s);
    }

    JSONArray array = new JSONArray(builder.toString());

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ", Locale.getDefault());

    ArrayList<Opening> openings = new ArrayList<>();

    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.getJSONObject(i);

        Date open = dateFormat.parse(object.getString("Open"));
        Date close = dateFormat.parse(object.getString("Close"));
        JSONArray nameArray = object.getJSONArray("Employees");
        List<String> names = new ArrayList<>();

        for (int j = 0; j < nameArray.length(); j++) {
            names.add(nameArray.getString(j));
        }

        openings.add(new Opening(open, close, names));
    }
    mOpeningsCache = openings;
    return openings;
}

From source file:de.onelogic.android.weatherdemo.WeatherFetchTask.java

private String downloadUrl(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);/* www.  j av  a  2s  . c  om*/
    // Starts the query
    conn.connect();
    InputStream is = conn.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    return sb.toString();
}

From source file:com.mnt.base.util.HttpUtil.java

public static String processPostRequest2Text(String url, Map<String, Object> parameters,
        Map<String, String> headerValue) {

    HttpURLConnection connection = null;

    try {// w  w  w .  j a v a  2  s  .  com
        connection = (HttpURLConnection) new URL(url).openConnection();
    } catch (IOException e) {
        log.error("Error while process http get request.", e);
    }

    if (connection != null) {
        try {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
        } catch (ProtocolException e) {
            log.error("should not happen to get error while set the request method as GET.", e);
        }

        if (!CommonUtil.isEmpty(headerValue)) {
            for (String key : headerValue.keySet()) {
                connection.setRequestProperty(key, headerValue.get(key));
            }
        }

        // need to specify the content type for post request
        connection.setRequestProperty("Content-Type", "application/json");

        setTimeout(connection);

        String resultStr = null;

        try {
            connection.connect();

            if (parameters != null) {
                String jsonParams = null;

                try {
                    jsonParams = JSONTool.convertObjectToJson(parameters);
                } catch (Exception e) {
                    log.error("error while process parameters to json string.", e);
                }

                if (jsonParams != null) {
                    connection.getOutputStream().write(jsonParams.getBytes());
                    connection.getOutputStream().flush();
                }
            }

            resultStr = readData(connection.getInputStream());
        } catch (IOException e) {
            log.error("fail to connect to url: " + url, e);
        } finally {
            connection.disconnect();
        }

        return resultStr;
    }

    return null;
}

From source file:cn.ctyun.amazonaws.internal.EC2MetadataClient.java

/**
 * Connects to the metadata service to read the specified resource and
 * returns the text contents.//from ww w  .j  a  v a  2s.  c o m
 *
 * @param resourcePath
 *            The resource
 *
 * @return The text payload returned from the Amazon EC2 Instance Metadata
 *         service for the specified resource path.
 *
 * @throws IOException
 *             If any problems were encountered while connecting to metadata
 *             service for the requested resource path.
 * @throws AmazonClientException
 *             If the requested metadata service is not found.
 */
public String readResource(String resourcePath) throws IOException, AmazonClientException {
    URL url = getEc2MetadataServiceUrlForResource(resourcePath);
    log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(1000 * 2);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();

    return readResponse(connection);
}

From source file:imdbdataextract.IMDBDataExtract.java

public String Login(String url) throws MalformedURLException, IOException {
    try {/*w w  w .j a  v a 2s  .  com*/
        //this.BaseUrl = "https://api.themoviedb.org/3/movie/"+str+"?api_key=ff952840f45b98d699b51692ac712cdd";
        //this.BaseUrl="https://api.themoviedb.org/3/genre/movie/list?api_key=ff952840f45b98d699b51692ac712cdd&language=en-US";
        this.BaseUrl = url;
        //this.BaseUrl="http://api.themoviedb.org/3/movie/"+str+"/videos?api_key=ff952840f45b98d699b51692ac712cdd";
        HttpURLConnection httpcon = (HttpURLConnection) ((new URL(BaseUrl).openConnection()));
        httpcon.setDoOutput(true);
        httpcon.connect();
        BufferedReader inreader = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = inreader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return "";
    }

}

From source file:it.evilsocket.dsploit.net.GitHubParser.java

private void fetchBranches() throws IOException, JSONException {
    HttpURLConnection connection;
    HttpURLConnection.setFollowRedirects(true);
    URL url = new URL(String.format(BRANCHES_URL, mUsername, mProject));
    connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    int ret = connection.getResponseCode();

    if (ret != 200)
        throw new IOException(String.format("unable to retrieve branches from github: '%s' => %d",
                String.format(BRANCHES_URL, mUsername, mProject), ret));

    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;//w  ww.ja v  a2s  .co  m

    while ((line = reader.readLine()) != null)
        sb.append(line);

    mBranches = new JSONArray(sb.toString());
}

From source file:de.micmun.android.workdaystarget.DayCalculator.java

/**
 * Returns the list with holydays between now and target.
 *
 * @return the list with holydays between now and target.
 * @throws JSONException if parsing the holidays fails.
 */// ww  w . ja  v a  2  s .  co m
private ArrayList<Date> getHolidays() throws JSONException {
    ArrayList<Date> holidays = new ArrayList<Date>();

    String basisUrl = "http://kayaposoft.com/enrico/json/v1.0/"
            + "?action=getPublicHolidaysForDateRange&fromDate=%s&toDate=%s" + "&country=ger&region=Bavaria";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());

    String url = String.format(basisUrl, sdf.format(today.getTime()), sdf.format(target.getTime()));
    BufferedReader br = null;
    String text = null;

    try {
        URL httpUrl = new URL(url);
        HttpURLConnection con = (HttpURLConnection) httpUrl.openConnection();
        con.setRequestMethod("GET");
        con.connect();
        InputStream is = con.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line;

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        br.close();
        text = sb.toString();
    } catch (MalformedURLException e) {
        System.err.println("FEHLER: " + e.getMessage());
        holidays = null;
    } catch (IOException e) {
        System.err.println("FEHLER: " + e.getMessage());
        holidays = null;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ignored) {
            }
        }
    }

    if (text != null) {
        JSONArray array = new JSONArray(text);
        for (int i = 0; i < array.length(); ++i) {
            JSONObject h = array.getJSONObject(i);
            JSONObject o = h.getJSONObject("date");
            int day = o.getInt("day");
            int month = o.getInt("month");
            int year = o.getInt("year");
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.DAY_OF_MONTH, day);
            cal.set(Calendar.MONTH, month - 1);
            cal.set(Calendar.YEAR, year);
            setMidnight(cal);
            holidays.add(cal.getTime());
        }
    }

    return holidays;
}