List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java
private static String get(String url_string) throws ClientException { HttpURLConnection connection = null; // NOTE: fetchImage is set up to use HTTP not HTTPS try {/*from w w w.jav a 2 s. c o m*/ URL url = new URL(url_string); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); InputStream is = new BufferedInputStream(connection.getInputStream()); int response_code; if ((response_code = connection.getResponseCode()) != 200) { throw new ClientException("Error code returned by response: " + response_code); } return InputStreamToString(is); } catch (SocketTimeoutException e) { throw new ClientException("Socket timed out.", e); } catch (IOException e) { throw new ClientException("IO Exception raised while attempting to GET response.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:Main.java
public static String doGet(String urlStr) { URL url = null;/*from w w w .j a v a 2 s. c om*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:com.cyphermessenger.client.SyncRequest.java
private static CypherContact manageContact(CypherSession session, String contactName, boolean add) throws IOException, APIErrorException { String action = "block"; if (add) {//from w w w . ja v a 2 s .c om action = "add"; } String[] keys = new String[] { "action", "contactName" }; String[] vals = new String[] { action, contactName }; HttpURLConnection conn = doRequest("contact", session, keys, vals); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); } InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode == StatusCode.OK && add) { long userID = node.get("contactID").asLong(); long keyTimestamp = node.get("keyTimestamp").asLong(); long contactTimestamp = node.get("contactTimestamp").asLong(); ECKey key = Utils.decodeKey(node.get("publicKey").asText()); key.setTime(keyTimestamp); boolean isFirst = node.get("isFirst").asBoolean(); return new CypherContact(contactName, userID, key, keyTimestamp, CypherContact.ACCEPTED, contactTimestamp, isFirst); } else { boolean isFirst = node.get("isFirst").asBoolean(); String status; switch (statusCode) { case StatusCode.CONTACT_WAITING: status = CypherContact.WAITING; break; case StatusCode.OK: case StatusCode.CONTACT_BLOCKED: status = CypherContact.BLOCKED; break; case StatusCode.CONTACT_DENIED: status = CypherContact.DENIED; break; default: throw new APIErrorException(statusCode); } return new CypherContact(contactName, null, null, null, status, null, isFirst); } }
From source file:Main.java
public static byte[] doGet(String urlStr) { URL url = null;/*from ww w. ja v a2 s . c o m*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toByteArray(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:eu.eexcess.ddb.recommender.PartnerConnector.java
/** * Opens a HTTP connection, gets the response and converts into to a String. * /*from ww w . j a va 2 s . c om*/ * @param urlStr Servers URL * @param properties Keys and values for HTTP request properties * @return Servers response * @throws IOException If connection could not be established or response code is !=200 */ public static String httpGet(String urlStr, HashMap<String, String> properties) throws IOException { if (properties == null) { properties = new HashMap<String, String>(); } // open HTTP connection with URL URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // set properties if any do exist for (String key : properties.keySet()) { conn.setRequestProperty(key, properties.get(key)); } // test if request was successful (status 200) if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } // buffer the result into a string InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); isr.close(); conn.disconnect(); return sb.toString(); }
From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java
protected static int insertDataPoints(String urlString, List<IncomingDataPoint> points) throws IOException { int code = 0; Gson gson = new Gson(); HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString); OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream()); String json = gson.toJson(points); wr.write(json);/*from www .j ava 2 s .c o m*/ wr.flush(); wr.close(); code = httpConnection.getResponseCode(); httpConnection.disconnect(); return code; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Checks if is reachable.//from ww w.ja v a 2 s . co m * * @param uri the uri * @param headers the headers * @return true, if is reachable */ public static boolean isReachable(String uri, HashMap<String, String> headers) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection(); myURLConnection.setRequestMethod("HEAD"); for (String key : headers.keySet()) { myURLConnection.setRequestProperty("Authorization", headers.get(key)); } LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString()); return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java
public static String getAuthToken(String server, String code) { String token = null;/*from w w w. j a v a2 s .co 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:ca.xecure.easychip.CommonUtilities.java
public static void http_post(String endpoint, Map<String, String> params) throws IOException { URL url;/* w w w. j a v a 2 s.c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } String body = JSONValue.toJSONString(params); 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", "application/json"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); 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.android.dialer.omni.PlaceUtil.java
/** * Executes a post request and return a JSON object * @param url The API URL/*from w w w.j a v a 2s . c om*/ * @param data The data to post in POST field * @return the JSON object * @throws IOException * @throws JSONException */ public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); if (DEBUG) Log.d(TAG, "Posting: " + postData + " to " + url); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return json; }