List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
static String getHttpString(String url) { String result = null;/* www.j av a 2s .com*/ // build connection HttpURLConnection huc = getHUC(url); huc.setInstanceFollowRedirects(false); try { // try to establish connection huc.connect(); // get result int responseCode = huc.getResponseCode(); Logd(TAG, "getHttpString response: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); } else { // result = "response code: "+responseCode; } // close connection huc.disconnect(); } catch (Exception e) { Log.e(TAG, "revokeSite FAILED"); e.printStackTrace(); } return result; }
From source file:crow.util.Util.java
public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException { int responseCode = -1; OutputStream osw = null;//from w ww . j a v a2s . co m try { conn.setConnectTimeout(20000); conn.setReadTimeout(12000); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); byte[] bytes = encodePostParam.getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(bytes.length)); osw = conn.getOutputStream(); osw.write(bytes); osw.flush(); responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new IOException(""); } else { String s = inputStreamToString(conn.getInputStream()); return s; } } finally { try { if (osw != null) osw.close(); } catch (Exception ignore) { } } }
From source file:com.dopecoin.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from ww w . ja v a 2s .com*/ URL providerUrl; switch (provider) { case 0: providerUrl = DOPEPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = DOPEPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("DOPE") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:in.leafco.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w w w .j a v a 2s . c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = LEAFPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = LEAFPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("LEAF") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:net.mutil.util.HttpUtil.java
public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap) throws ClientProtocolException, IOException { String strResult = ""; URL url = new URL(HttpUtil.getPCURL() + strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); StringBuilder entitySb = new StringBuilder(""); Object[] entityKeys = entityMap.keySet().toArray(); for (int i = 0; i < entityKeys.length; i++) { String key = (String) entityKeys[i]; if (i == 0) { entitySb.append(key + "=" + entityMap.get(key)); } else {//from w w w.j a v a2 s .c om entitySb.append("&" + key + "=" + entityMap.get(key)); } } byte[] entity = entitySb.toString().getBytes("UTF-8"); System.out.println(url.toString() + entitySb.toString()); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); conn.getOutputStream().write(entity); if (conn.getResponseCode() == 200) { InputStream inputstream = conn.getInputStream(); StringBuffer buffer = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = inputstream.read(b)) != -1;) { buffer.append(new String(b, 0, n)); } strResult = buffer.toString(); } return strResult; }
From source file:de.jdellay.wallet.ExchangeRatesProvider.java
private static float requestCcnBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w w w. j a va 2 s . c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = CCNPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = CCNPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("CCN") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:com.melniqw.instagramsdk.Network.java
private static String sendDummyRequest(String url, String body, Request request) throws IOException { HttpURLConnection connection = null; try {/*from w w w. ja va2 s.com*/ connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); if (request == Request.GET) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else if (request == Request.POST) { connection.setDoOutput(true); connection.setRequestMethod("POST"); } if (REQUEST_ENABLE_COMPRESSION) connection.setRequestProperty("Accept-Encoding", "gzip"); if (request == Request.POST) connection.getOutputStream().write(body.getBytes("utf-8")); int code = connection.getResponseCode(); System.out.println(TAG + " responseCode = " + code); //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation if (code == -1) throw new WrongResponseCodeException("Network error"); // ? 200 //on error can also read error stream from connection. InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192); String encoding = connection.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) inputStream = new GZIPInputStream(inputStream); String response = Utils.convertStreamToString(inputStream); System.out.println(TAG + " response = " + response); return response; } finally { if (connection != null) connection.disconnect(); } }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean put(String bucketName, String objectKey, byte[] data, String contentType, boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException { final byte[] md5Raw = MD5Util.md5(data); final String md5Base64 = Base64.encodeBase64String(md5Raw).trim(); final String md5Hex = MD5Util.toHex(md5Raw); final String date = getDate(); final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE; final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); final URL url = new URL(String.format(S3_URL, bucketName, objectKey)); OutputStream out = null;/*from w ww . jav a 2s. c o m*/ HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-MD5", md5Base64); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Date", date); if (isPublic) { // If we don't send this header, the object will be private by default conn.setRequestProperty("x-amz-acl", "public-read"); } conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); out = new BufferedOutputStream(conn.getOutputStream()); IOUtils.copy(new ByteArrayInputStream(data), out); out.flush(); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error uploading file: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } String etag = conn.getHeaderField("ETag"); etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes if (!md5Hex.equals(etag)) { log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(out); } }
From source file:disko.DU.java
public static String request(String targetUrl, String method, String text, String contentType) throws Exception { URL url = new URL(targetUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (method != null) conn.setRequestMethod(method);/*from w ww . j av a 2 s.c om*/ if (contentType != null) conn.setRequestProperty("Content-Type", contentType); if (text != null) { conn.setDoOutput(true); conn.setUseCaches(false); conn.getOutputStream().write(text.getBytes()); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(text.getBytes()); out.flush(); out.close(); } if (conn.getResponseCode() != 200) throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode()); StringBuffer responseBuffer = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String eol = new String(new byte[] { 13 }); while ((line = in.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(eol); } in.close(); return responseBuffer.toString(); }
From source file:Main.java
public Main() { JPanel inputPanel = new JPanel(new BorderLayout(3, 3)); go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { URL pageURL = new URL("http://www.google.com"); HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection(); int respCode = urlConnection.getResponseCode(); String response = urlConnection.getResponseMessage(); codeArea.setText("HTTP/1.x " + respCode + " " + response + "\n"); int count = 1; while (true) { String header = urlConnection.getHeaderField(count); String key = urlConnection.getHeaderFieldKey(count); if (header == null || key == null) { break; }//from www .j a v a2s .c o m codeArea.append(urlConnection.getHeaderFieldKey(count) + ": " + header + "\n"); count++; } InputStream in = new BufferedInputStream(urlConnection.getInputStream()); Reader r = new InputStreamReader(in); int c; while ((c = r.read()) != -1) { codeArea.append(String.valueOf((char) c)); } codeArea.setCaretPosition(1); } catch (Exception ee) { } } }); inputPanel.add(BorderLayout.EAST, go); JScrollPane codeScroller = new JScrollPane(codeArea); add(BorderLayout.NORTH, inputPanel); add(BorderLayout.CENTER, codeScroller); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(700, 500); this.setVisible(true); }