List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.fota.Link.sdpApi.java
public static String getCtnInfo(String ncn) throws JDOMException { String resultStr = ""; String logData = ""; try {// w w w. j a va2 s .c om String cpId = PropUtil.getPropValue("sdp3g.id"); String cpPw = PropUtil.getPropValue("sdp3g.pw"); String authorization = cpId + ":" + cpPw; logData = "\r\n---------- Get Ctn Req Info start ----------\r\n"; logData += " getCtnRequestInfo - authorization : " + authorization; byte[] encoded = Base64.encodeBase64(authorization.getBytes()); authorization = new String(encoded); String contractType = "0"; String contractNum = ncn.substring(0, 9); String customerId = ncn.substring(10, ncn.length() - 1); JSONObject reqJObj = new JSONObject(); reqJObj.put("transactionid", ""); reqJObj.put("sequenceno", ""); reqJObj.put("userid", ""); reqJObj.put("screenid", ""); reqJObj.put("CONTRACT_NUM", contractNum); reqJObj.put("CUSTOMER_ID", customerId); reqJObj.put("CONTRACT_TYPE", contractType); authorization = "Basic " + authorization; String endPointUrl = PropUtil.getPropValue("sdp.oif555.url"); logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl; logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization; logData += "\r\n getCtnRequestInfo - Content-type : application/json"; logData += "\r\n getCtnRequestInfo - RequestMethod : POST"; logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString(); logData += "\r\n---------- Get Ctn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", authorization); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(reqJObj.toJSONString()); wr.flush(); wr.close(); // input BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine = ""; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONParser jsonParser = new JSONParser(); JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString()); // String respTransactionId = (String) respJsonObject.get("transactionid"); // String respSequenceNo = (String) respJsonObject.get("sequenceno"); // String respReturnCode = (String) respJsonObject.get("returncode"); // String respReturnDescription = (String) respJsonObject.get("returndescription"); // String respErrorCode = (String) respJsonObject.get("errorcode"); // String respErrorDescription = (String) respJsonObject.get("errordescription"); String respCtn = (String) respJsonObject.get("ctn"); // String respSubStatus = (String) respJsonObject.get("sub_status"); // String respSubStatusDate = (String) respJsonObject.get("sub_status_date"); resultStr = respCtn; //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:de.langerhans.wallet.ExchangeRatesProvider.java
private static double requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w w w . j a va2s . c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = CRYPTSY_URL; break; case 1: providerUrl = BTER_URL; break; default: providerUrl = CRYPTSY_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)); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { final JSONObject json = new JSONObject(content.toString()); double rate; boolean success; switch (provider) { case 0: success = json.getBoolean("success"); if (!success) { return -1; } rate = json.getJSONObject("data").getJSONObject("last_trade").getDouble("price"); break; case 1: success = json.getString("result").equals("true"); // Eww bad API! if (!success) { return -1; } rate = Double.valueOf(json.getString("last")); 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.kiwiteam.nomiddleman.TourPageActivity.java
/** * Checks if link is active/* w w w. j av a2s . c o m*/ * @param urlString * @return * @throws MalformedURLException * @throws IOException */ public static int getResponseCode(String urlString) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); huc.connect(); return huc.getResponseCode(); }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
/** * Apply normalization rules to the identifier supplied by the End-User * to determine the Resource and Host. Then make an HTTP GET request to * the host's WebFinger endpoint to obtain the location of the requested * service/*www .ja v a2 s . c o m*/ * return the issuer location ("href") * @param user_input , domain * @return */ public static String webfinger(String userInput, String serverUrl) { // android.os.Debug.waitForDebugger(); String result = ""; // result of the http request (a json object // converted to string) String postUrl = ""; String host = null; String href = null; // URI identifying the type of service whose location is being requested final String rel = "http://openid.net/specs/connect/1.0/issuer"; if (!isEmpty(userInput)) { try { // normalizes this URI's path URI uri = new URI(userInput).normalize(); String[] parts = uri.getRawSchemeSpecificPart().split("@"); if (!isEmpty(serverUrl)) { // use serverUrl if specified if (serverUrl.startsWith("https://")) { host = serverUrl.substring(8); } else if (serverUrl.startsWith("http://")) { host = serverUrl.substring(7); } else { host = serverUrl; } } else if (parts.length > 1) { // the user is using an E-Mail Address Syntax host = parts[parts.length - 1]; } else { // the user is using an other syntax host = uri.getHost(); } // check if host is valid if (host == null) { return null; } if (!host.endsWith("/")) host += "/"; postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel; // log the request Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host); // Send an HTTP get request with the resource and rel parameters HttpURLConnection huc = getHUC(postUrl); huc.setDoOutput(true); huc.setRequestProperty("Content-Type", "application/jrd+json"); huc.connect(); try { int responseCode = huc.getResponseCode(); Logd(TAG, "webfinger responseCode: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); Logd(TAG, "webfinger result: " + result); // The response is a json object and the issuer location // is returned as the value of the href member // a links array element with the rel member value // http://openid.net/specs/connect/1.0/issuer JSONObject jo = new JSONObject(result); JSONObject links = jo.getJSONArray("links").getJSONObject(0); href = links.getString("href"); Logd(TAG, "webfinger reponse href: " + href); } else { // why the request didn't succeed href = huc.getResponseMessage(); } // close connection huc.disconnect(); } catch (IOException ioe) { Logd(TAG, "webfinger io exception: " + huc.getErrorStream()); ioe.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } else { // the user_input is empty href = "no identifier detected!!\n"; } return href; }
From source file:oauth.signpost.basic.DefaultOAuthProvider.java
protected HttpResponse sendRequest(HttpRequest request) throws IOException { HttpURLConnection connection = (HttpURLConnection) request.unwrap(); connection.connect(); return new HttpURLConnectionResponseAdapter(connection); }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a string via POST to a given url. * * @param context the context to use. * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message. * @return the response./* w w w . jav a 2s .c om*/ * @throws Exception if something goes wrong. */ public static String sendPost(Context context, String urlStr, String string, String user, String password, boolean readResponse) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); if (readResponse) { StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } else { return getMessageForCode(context, responseCode, context.getResources().getString(R.string.post_completed_properly)); } } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.bellman.bible.service.common.CommonUtils.java
/** return true if URL is accessible * /*from w w w . jav a 2 s. c o m*/ * Since Android 3 must do on different or NetworkOnMainThreadException is thrown */ public static boolean isHttpUrlAvailable(final String urlString) { boolean isAvailable = false; final int TIMEOUT_MILLIS = 3000; try { class CheckUrlThread extends Thread { public boolean checkUrlSuccess = false; public void run() { HttpURLConnection connection = null; try { // might as well test for the url we need to access URL url = new URL(urlString); Log.d(TAG, "Opening test connection"); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIMEOUT_MILLIS); connection.setReadTimeout(TIMEOUT_MILLIS); connection.setRequestMethod("HEAD"); Log.d(TAG, "Connecting to test internet connection"); connection.connect(); checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK); Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess); } catch (IOException e) { Log.i(TAG, "No internet connection"); checkUrlSuccess = false; } finally { if (connection != null) { connection.disconnect(); } } } } CheckUrlThread checkThread = new CheckUrlThread(); checkThread.start(); checkThread.join(TIMEOUT_MILLIS); isAvailable = checkThread.checkUrlSuccess; } catch (InterruptedException e) { Log.e(TAG, "Interrupted waiting for url check to complete", e); } return isAvailable; }
From source file:com.maltera.technologic.maven.mcforge.detect.CentralHashDetector.java
public void detect(Target target) throws MojoFailureException, MojoExecutionException { try {//from ww w. j a v a2s . com final URL url = new URL("http://search.maven.org/solrsearch/select" + "?q=1:\"" + target.getHash() + "\"&rows=1&wt=json"); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); if (200 != conn.getResponseCode()) { throw new MojoFailureException("error querying Nexus on Maven Central: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } final JsonNode result = jackson.readTree(conn.getInputStream()); final JsonNode artifact = result.path("response").path("docs").path(0); if (!artifact.isMissingNode()) { target.foundArtifact( new DefaultArtifact(artifact.path("g").textValue(), artifact.path("a").textValue(), artifact.path("p").textValue(), artifact.path("v").textValue()), "central"); } } catch (IOException caught) { throw new MojoFailureException("error searching Maven Central", caught); } }
From source file:com.aperlambda.apercommon.connection.http.HttpRequestSender.java
private HttpResponse send(HttpURLConnection connection) throws IOException { connection.connect(); if (connection.getResponseCode() != 200) return new HttpResponse(connection.getResponseCode()); Map<String, String> headers = new HashMap<>(); connection.getHeaderFields().forEach((key, value) -> headers.put(key, value.get(0))); String body;/*from w w w . j a v a 2s . co m*/ InputStream iStream = null; try { iStream = connection.getInputStream(); String encoding = connection.getContentEncoding(); encoding = encoding == null ? "UTF-8" : encoding; body = IOUtils.toString(iStream, encoding); } finally { if (iStream != null) { iStream.close(); } } if (body == null) { throw new IOException("Unparseable response body! \n {" + body + "}"); } return new HttpResponse(connection.getResponseCode(), headers, body); }
From source file:com.mebigfatguy.polycasso.URLFetcher.java
/** * retrieve arbitrary data found at a specific url * - either http or file urls// w ww .j a va2 s .c o m * for http requests, sets the user-agent to mozilla to avoid * sites being cranky about a java sniffer * * @param url the url to retrieve * @param proxyHost the host to use for the proxy * @param proxyPort the port to use for the proxy * @return a byte array of the content * * @throws IOException the site fails to respond */ public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException { HttpURLConnection con = null; InputStream is = null; try { URL u = new URL(url); if (url.startsWith("file://")) { is = new BufferedInputStream(u.openStream()); } else { Proxy proxy; if (proxyHost != null) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = Proxy.NO_PROXY; } con = (HttpURLConnection) u.openConnection(proxy); con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6"); con.addRequestProperty("Accept-Charset", "UTF-8"); con.addRequestProperty("Accept-Language", "en-US,en"); con.addRequestProperty("Accept", "text/html,image/*"); con.setDoInput(true); con.setDoOutput(false); con.connect(); is = new BufferedInputStream(con.getInputStream()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); return baos.toByteArray(); } finally { IOUtils.closeQuietly(is); if (con != null) { con.disconnect(); } } }