List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;//from w w w. j a v a 2 s .c om try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BTCE_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;/* www. j ava 2 s . c om*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendPost() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {//from ww w . j a v a 2 s . com //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenPost.php"; //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON URL obj = new URL(url); //Creamos un objeto de conexin HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //Aadimos la cabecera con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //Creamos los parametros para enviar String urlParameters = "json=" + jsonString; // Enviamos los datos por POST con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Capturamos la respuesta del servidor int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } //Mostramos la respuesta del servidor por consola System.out.println(response); //cerramos la conexin in.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java
private static String read(final URL url, final String httpAuthBase64, final HostnameVerifier hostnameVerifier) throws IOException { StringBuffer sb = new StringBuffer(1024); HttpURLConnection connection = null; connection = (HttpURLConnection) url.openConnection(); if (url.getProtocol().equalsIgnoreCase("https")) { connection = (HttpsURLConnection) url.openConnection(); ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier); }// ww w .j a v a2 s . com if (httpAuthBase64 != null) { connection.setRequestProperty("Authorization", new StringBuffer(httpAuthBase64.length() + 6) .append("Basic ").append(httpAuthBase64).toString()); } connection.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\""); connection.setRequestMethod("GET"); int returnCode = connection.getResponseCode(); InputStream connectionIn = null; if (returnCode == 200) { connectionIn = connection.getInputStream(); } else { connectionIn = connection.getErrorStream(); } BufferedReader buffer = new BufferedReader(new InputStreamReader(connectionIn)); String inputLine; while ((inputLine = buffer.readLine()) != null) { sb.append(inputLine); } buffer.close(); return sb.toString(); }
From source file:no.ntnu.wifimanager.ServerUtilities.java
/** * Issue a POST request to server./*from w ww. ja va2s . co m*/ * * @param serverUrl POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType) throws IOException { URL url; try { url = new URL(serverUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + serverUrl); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(LOG_TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<User> getAllUsers() throws IOException { String _url = getBaseUri().appendPath("Users").build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/*from w w w . j a v a 2 s . c o m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); List<User> userList = new ArrayList<User>(); final JsonNode userArray = MAPPER.readTree(response).get(Keys.User.LIST); if (userArray.isArray()) { for (final JsonNode userNode : userArray) { User u = parseUser(userNode); // assign and check null and do not add local user if (u != null) { userList.add(u); } } } conn.disconnect(); return userList; }
From source file:net.ftb.util.DownloadUtils.java
/** * Checks the file for corruption./* w ww. j a v a2s. co m*/ * @param file - File to check * @param url - base url to grab md5 with old method * @return boolean representing if it is valid * @throws IOException */ public static boolean backupIsValid(File file, String url) throws IOException { Logger.logInfo("Issue with new md5 method, attempting to use backup method."); String content = null; Scanner scanner = null; String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/md5/FTB2/" + url; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); int response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); } if (response != 200 || (content == null || content.isEmpty())) { for (String server : backupServers.values()) { resolved = "http://" + server + "/md5/FTB2/" + url.replace("/", "%5E"); connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); if (content != null && !content.isEmpty()) { break; } } } } } catch (IOException e) { } finally { connection.disconnect(); if (scanner != null) { scanner.close(); } } String result = fileMD5(file); Logger.logInfo("Local: " + result.toUpperCase()); Logger.logInfo("Remote: " + content.toUpperCase()); return content.equalsIgnoreCase(result); }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Project> getProject(String userID) throws IOException { // Server URL setup String _url = getBaseUri().appendPath("Projects").appendPath(userID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/* w w w .j a va2 s .co m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper List<Project> projectList = new ArrayList<Project>(); final JsonNode projectArray = MAPPER.readTree(response).get(Keys.Project.LIST); if (projectArray.isArray()) { for (final JsonNode projectNode : projectArray) { Project p = new Project(); p.setProjectID(projectNode.get(Keys.Project.ID).asText()); ProjectDatabaseAdapter.getProject(p); if (p.getProjectID() != null && !p.getProjectID().isEmpty()) { projectList.add(p); } } } else { Log.e(TAG, "Error parsing user's project list"); } conn.disconnect(); return projectList; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Meeting> getMeetings(String userID) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath("Meetings").appendPath(userID).build().toString(); // establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod("GET"); addRequestHeader(conn, false);//from w w w. jav a 2s .co m // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper List<Meeting> meetingsList = new ArrayList<Meeting>(); List<String> meetingIDList = new ArrayList<String>(); JsonNode responseNode = MAPPER.readTree(response); final JsonNode meetingsArray = responseNode.get(Keys.Meeting.LIST); if (meetingsArray != null && meetingsArray.isArray()) { for (final JsonNode meetingNode : meetingsArray) { String _id = meetingNode.get(Keys._ID).asText(); if (!meetingNode.get("type").asText().equals("MADE_MEETING")) { meetingIDList.add(_id); } } } else { logError(TAG, responseNode); } conn.disconnect(); for (String id : meetingIDList) { meetingsList.add(MeetingDatabaseAdapter.getMeetingInfo(id)); } return meetingsList; }
From source file:com.talk.demo.util.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password./*from w w w .j a v a 2 s. c om*/ * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ /* public static String authenticate(String username, String password) { final HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); final HttpEntity entity; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new IllegalStateException(e); } Log.i(TAG, "Authenticating to: " + AUTH_URI); final HttpPost post = new HttpPost(AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); try { resp = getHttpClient().execute(post); String authToken = null; if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream istream = (resp.getEntity() != null) ? resp.getEntity().getContent() : null; if (istream != null) { BufferedReader ireader = new BufferedReader(new InputStreamReader(istream)); authToken = ireader.readLine().trim(); } } if ((authToken != null) && (authToken.length() > 0)) { Log.v(TAG, "Successful authentication"); return authToken; } else { Log.e(TAG, "Error authenticating" + resp.getStatusLine()); return null; } } catch (final IOException e) { Log.e(TAG, "IOException when getting authtoken", e); return null; } finally { Log.v(TAG, "getAuthtoken completing"); } } */ public static String signup(String username, String email, String password) { String authToken = null; String csrfToken2 = null; try { HttpURLConnection conn = HttpRequest.get(SIGNUP_URI).getConnection(); //ToDo: cookie header may be null, should fix it. List<String> cookieHeader = conn.getHeaderFields().get("Set-Cookie"); for (String resItem : cookieHeader) { Log.d(TAG, "cookie session: " + resItem); if (resItem.contains("sessionid")) { authToken = resItem.split(";")[0]; Log.d(TAG, "session :" + authToken); } if (resItem.contains("csrftoken")) { csrfToken2 = resItem.split(";")[0]; Log.d(TAG, "csrf token :" + csrfToken2); } } Log.d(TAG, "cookie: " + cookieHeader); String csrfToken = csrfToken2; Log.d(TAG, "csrf token : " + csrfToken); HttpRequest request = HttpRequest.post(SIGNUP_URI); String name = username; String mail = email; String passwd = password; Map<String, String> data = new HashMap<String, String>(); data.put("username", name); data.put("email", mail); data.put("password", passwd); data.put("password_confirm", passwd); data.put("csrfmiddlewaretoken", csrfToken.substring(10)); Log.d(TAG, "name: " + username + " passwd: " + password); // X-CSRFToken Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "text/html"); headers.put("Cookie", csrfToken); Log.d(TAG, "our cookie: " + csrfToken); request.headers(headers); //request.followRedirects(false); HttpRequest conn4Session = request.form(data); conn4Session.code(); HttpURLConnection sessionConnection = conn4Session.getConnection(); try { int result = sessionConnection.getResponseCode(); Log.e(TAG, "get response code : " + result); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (HttpRequestException exception) { Log.d(TAG, "exception : " + exception.toString()); return null; } finally { Log.v(TAG, "signup completing"); } return "ok"; }