List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:br.eb.ime.pfc.domain.GeoServerCommunication.java
private static void redirectStream(String urlName, HttpServletRequest request, HttpServletResponse response) { URL url = null;// w w w.ja v a 2 s. com try { url = new URL(urlName); } catch (MalformedURLException e) { //Internal error, the user will receive no data. sendError(HTTP_STATUS.BAD_REQUEST, response); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Authorization", "Basic " + BASE64_AUTHORIZATION); //conn.setRequestMethod("GET"); //conn.setDoOutput(true); conn.connect(); } catch (IOException e) { sendError(HTTP_STATUS.INTERNAL_ERROR, response); return; } try (InputStream is = conn.getInputStream(); OutputStream os = response.getOutputStream()) { response.setContentType(conn.getContentType()); IOUtils.copy(is, os); } catch (IOException e) { request.getServletContext().log("IO"); sendError(HTTP_STATUS.INTERNAL_ERROR, response); return; } finally { //Close connection to save resources conn.disconnect(); } }
From source file:controllers.base.Application.java
public static Result login(String redirectTo, boolean isGuest) { if (isGuest) { createWebSession();/* w ww .ja v a2s .co m*/ } else { String token = request().body().asFormUrlEncoded().get("token")[0]; String apiKey = Play.application().configuration().getString("rpx.apiKey"); String data; String response = null; try { data = String.format("token=%s&apiKey=%s&format=json", URLEncoder.encode(token, "UTF-8"), URLEncoder.encode(apiKey, "UTF-8")); URL url = new URL("https://rpxnow.com/api/v2/auth_info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw.write(data); osw.close(); response = IOUtils.toString(conn.getInputStream()); } catch (IOException e) { throw new IllegalArgumentException(e); } JsonNode profile = Json.parse(response).path("profile"); String identifier = profile.path("identifier").asText(); WebUser user = WebUser.find.where().like("providerId", identifier).findUnique(); if (user == null) { user = new WebUser().setProviderId(identifier).setProfile(Json.stringify(profile)); user.save(); } createWebSession(user); } return postLoginRedirect(redirectTo); }
From source file:org.openbmap.soapclient.CheckServerTask.java
/** * Checks connection to openbmap.org// ww w. j av a2 s. c o m * @return true on successful http connection */ private static boolean isOnline() { try { Log.v(TAG, "Ping " + Preferences.VERSION_CHECK_URL); final URL url = new URL(Preferences.VERSION_CHECK_URL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Connection", "close"); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.connect(); if (connection.getResponseCode() == 200) { Log.i(TAG, String.format("Good: Server reply %s - device & server online", connection.getResponseCode())); return true; } else { Log.w(TAG, String.format("Bad: Http ping failed (server reply %s).", connection.getResponseCode())); } } catch (final IOException e) { Log.w(TAG, "Bad: Http ping failed (no response).."); } return false; }
From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java
public static String getAuthToken(String server, String code) { String token = null;//w w w . jav a 2 s. c o m final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_CODE, code)); params.add(new BasicNameValuePair(PARAM_CLIENT_SECRET, CLIENT_SECRET)); InputStream is = null; URL auth_token_url; try { auth_token_url = getRequestURL(server, PATH_OAUTH_ACCESS_TOKEN, params); Log.i(TAG, auth_token_url.toString()); HttpURLConnection conn = (HttpURLConnection) auth_token_url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response_code = conn.getResponseCode(); Log.d(TAG, "The response is: " + response_code); is = conn.getInputStream(); // parse token_response as JSON to get the token out String str_response = readStreamToString(is, 500); Log.d(TAG, str_response); JSONObject response = new JSONObject(str_response); token = response.getString("access_token"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Makes sure that the InputStream is closed after the app is // finished using it. if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Log.i(TAG, token); return token; }
From source file:com.example.android.didyoufeelit.Utils.java
/** * Make an HTTP request to the given URL and return a String as the response. *//* w w w. j av a 2s . co m*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:com.samsung.msf.youtubeplayer.client.util.FeedParser.java
/** * Given a string representation of a URL, sets up a connection and gets an input stream. *///w w w .java2 s. c om public static InputStream downloadUrl(final URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */); conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); return conn.getInputStream(); }
From source file:com.hichinaschool.flashcards.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {// w w w. ja v a2s . co m try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "com.hichinaschool.flashcards.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.connect(); File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }
From source file:Main.java
public static String stringFromHttpPost(String urlStr, String body) { HttpURLConnection conn; try {//from w w w. jav a 2 s.c o m URL e = new URL(urlStr); conn = (HttpURLConnection) e.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestMethod("POST"); OutputStream os1 = conn.getOutputStream(); DataOutputStream out1 = new DataOutputStream(os1); out1.write(body.getBytes("UTF-8")); out1.flush(); conn.connect(); String line; BufferedReader reader; StringBuffer sb = new StringBuffer(); if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) { reader = new BufferedReader( new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8")); } else { reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); logError(e.getMessage()); } return null; }
From source file:de.Keyle.MyPet.api.Util.java
public static String readUrlContent(String address, int timeout) throws IOException { StringBuilder contents = new StringBuilder(2048); BufferedReader br = null;/* w w w . j av a2 s . c o m*/ try { URL url = new URL(address); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout); huc.setRequestMethod("GET"); huc.connect(); br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String line; while ((line = br.readLine()) != null) { contents.append(line); } } finally { try { if (br != null) { br.close(); } } catch (Exception e) { e.printStackTrace(); } } return contents.toString(); }
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;/*from w w w .j a v a2s .c o m*/ URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }