List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
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 ww w . jav a 2s .co m 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 void server2mobile(Context context, String type) { String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type; try {/* www.ja v a2 s. c o m*/ URL url = new URL(serverPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); Log.d("code", code + ""); if (code == 200) { InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); conn.disconnect(); String result = new String(baos.toByteArray()); String[] results = result.split("[$]"); for (String r : results) { if (r.length() != 0) { URL json = new URL(r); HttpURLConnection con = (HttpURLConnection) json.openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); int co = con.getResponseCode(); if (co == 200) { File jsonFile; if (r.endsWith("clear.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/clear.json"); } else if (r.endsWith("crowd.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json"); } else if (r.endsWith("trouble.json")) { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json"); } else { jsonFile = new File( Environment.getExternalStorageDirectory() + "/traffic_json/control.json"); } if (jsonFile.exists()) jsonFile.delete(); jsonFile.createNewFile(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), "gb2312")); BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) { String line = null; while ((line = reader.readLine()) != null) { writer.write(line); } } } con.disconnect(); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static Boolean deleteNote(String noteID) throws IOException { String _url = getBaseUri().appendPath(noteID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);//from w w w . j a v a 2 s . c o m int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); boolean result = false; JsonNode tree = MAPPER.readTree(response); if (!response.isEmpty()) { if (!tree.has(Keys.DELETED)) { result = true; } else { logError("note.del.err", tree); } } conn.disconnect(); return result; }
From source file:Main.java
public static String httpGet(String urlStr, List<NameValuePair> params) { String paramsEncoded = ""; if (params != null) { paramsEncoded = URLEncodedUtils.format(params, "UTF-8"); }/*from w w w . j a v a2s . com*/ String fullUrl = urlStr + "?" + paramsEncoded; String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(fullUrl); connection = (HttpURLConnection) url.openConnection(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
From source file:ca.xecure.easychip.CommonUtilities.java
public static void http_post(String endpoint, Map<String, String> params) throws IOException { URL url;/*ww w . j av a2 s . co 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.meetingninja.csse.database.TaskDatabaseAdapter.java
public static Boolean deleteTask(String taskID) throws IOException { String _url = getBaseUri().appendPath(taskID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);/*from w w w .j ava 2 s. c o m*/ int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); boolean result = false; JsonNode tree = MAPPER.readTree(response); if (!response.isEmpty()) { if (!tree.has(Keys.DELETED)) { result = true; } else { logError(TAG, tree); } } conn.disconnect(); return result; }
From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java
public static void doDelete(String urls, String token) { URL url = null;/*from w w w . j a v a 2 s .c om*/ try { url = new URL(urls); } catch (MalformedURLException exception) { exception.printStackTrace(); } HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Content-Type", "application/json"); if (!Global.isEmpty(token)) { httpURLConnection.setRequestProperty("X-Auth-Token", token); } httpURLConnection.setRequestMethod("DELETE"); logger.info("#####====" + httpURLConnection.getResponseCode()); } catch (IOException e) { logger.error("Exception", e); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
From source file:edu.stanford.epadd.launcher.Main.java
private static boolean isURLAlive(String url) throws IOException { try {/*from w ww . jav a 2s.c o m*/ // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false // since "index" may auto load default archive, attach it to session, and redirect to "info" page, // we need to maintain the session across the pages. // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { } return false; }
From source file:com.wisdombud.right.client.common.HttpKit.java
/** * Send POST request//from www .j a va 2 s. c o m */ public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); conn.connect(); final OutputStream out = conn.getOutputStream(); out.write(data != null ? data.getBytes(CHARSET) : null); out.flush(); out.close(); return readResponseString(conn); } catch (final Exception e) { throw new RuntimeException(e); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.gallatinsystems.common.util.S3Util.java
public static String getObjectAcl(String bucketName, String objectKey, String awsAccessId, String awsSecretKey) throws IOException { final String date = getDate(); final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl"); final String payload = String.format(GET_PAYLOAD_ACL, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); InputStream in = null;//from w w w .j a v a 2 s.co m HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Date", date); conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); in = new BufferedInputStream(conn.getInputStream()); return IOUtils.toString(in); } catch (Exception e) { log.log(Level.SEVERE, "Error getting ACL for : " + url.toString(), e); return null; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(in); } }