List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.alexoree.jenkins.Main.java
private static String download(String localName, String remoteUrl) throws Exception { URL obj = new URL(remoteUrl); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000);/*from www.j ava 2 s . c o m*/ System.out.println("Request URL ... " + remoteUrl); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1, newUrl.lastIndexOf("/")); String pluginname = localName.substring(localName.lastIndexOf("/") + 1); String ext = ""; if (pluginname.endsWith(".war")) ext = ".war"; else ext = ".hpi"; pluginname = pluginname.replace(ext, ""); localName = localName.replace(pluginname + ext, "/download/plugins/" + pluginname + "/" + version + "/"); new File(localName).mkdirs(); localName += pluginname + ext; System.out.println("Redirect to URL : " + newUrl); } if (new File(localName).exists()) { System.out.println(localName + " exists, skipping"); return localName; } byte[] buffer = new byte[2048]; FileOutputStream baos = new FileOutputStream(localName); InputStream inputStream = conn.getInputStream(); int totalBytes = 0; int read = inputStream.read(buffer); while (read > 0) { totalBytes += read; baos.write(buffer, 0, read); read = inputStream.read(buffer); } System.out.println("Retrieved " + totalBytes + "bytes"); return localName; }
From source file:com.mobile.godot.core.controller.CoreController.java
public synchronized void register(UserBean user) { String servlet = "AddUser"; List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("firstname", user.getFirstname())); params.add(new BasicNameValuePair("lastname", user.getLastname())); params.add(new BasicNameValuePair("mail", user.getMail())); params.add(new BasicNameValuePair("username", user.getUsername())); params.add(new BasicNameValuePair("password", user.getPassword())); SparseIntArray mMessageMap = new SparseIntArray(); mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Session.REGISTERED); mMessageMap.append(HttpURLConnection.HTTP_CONFLICT, GodotMessage.Error.CONFLICT); mMessageMap.append(HttpURLConnection.HTTP_NOT_ACCEPTABLE, GodotMessage.Error.UNACCEPTABLE); GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler); Thread tAction = new Thread(action); tAction.start();/* w w w .j a v a2s . c o m*/ }
From source file:com.github.hexocraftapi.updater.updater.Downloader.java
/** * Download the file and save it to the updater folder. */// ww w.j av a 2s.c o m private boolean downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { // Init connection HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl()); // always check HTTP response code first int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); connection = (HttpURLConnection) initConnection(new URL(newUrl)); responseCode = connection.getResponseCode(); } // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String fileURL = this.update.getDownloadUrl().toString(); String disposition = connection.getHeaderField("Content-Disposition"); String contentType = connection.getContentType(); int fileLength = connection.getContentLength(); // extracts file name from header field if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) fileName = disposition.substring(index + 10, disposition.length() - 1); } // extracts file name from URL else fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); // opens input stream from the HTTP connection in = new BufferedInputStream(connection.getInputStream()); // opens an output stream to save into file fout = new FileOutputStream(new File(this.updateFolder, fileName)); log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString()); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) fout.write(buffer, 0, bytesRead); log(Level.INFO, "File downloaded: " + fileName); } } catch (Exception ex) { log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful."); return false; } finally { try { if (in != null) in.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } try { if (fout != null) fout.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } return true; } }
From source file:com.shuffle.bitcoin.blockchain.Btcd.java
/** * This method takes in a transaction hash and returns a bitcoinj transaction object. *///from ww w .j ava 2 s . c o m synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException { org.bitcoinj.core.Transaction tx = null; String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"getrawtransaction\", \"params\":[\"" + transactionHash + "\"]}"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject json = new JSONObject(response.toString()); String hexTx = (String) json.get("result"); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(hexTx); Context context = Context.getOrCreate(netParams); tx = new org.bitcoinj.core.Transaction(netParams, bytearray); } out.flush(); out.close(); return tx; }
From source file:hudson.plugins.sitemonitor.SiteMonitorDescriptor.java
/** * @return the success response codes/*from w ww.jav a2 s . c o m*/ */ public final List<Integer> getSuccessResponseCodes() { if (mSuccessResponseCodes == null) { mSuccessResponseCodes = new ArrayList<Integer>(); mSuccessResponseCodes.add(HttpURLConnection.HTTP_OK); } return mSuccessResponseCodes; }
From source file:eionet.cr.util.URLUtil.java
/** * Connect to the URL and check if it is modified since the timestamp argument. Returns null, if it cannot be determined for * sure.//from w w w.j a v a2 s . c o m * * @param urlString * @param timestamp * @return true if it is modified. */ public static Boolean isModifiedSince(String urlString, long timestamp) { if (!URLUtil.isURL(urlString)) { return Boolean.FALSE; } if (timestamp == 0) { return Boolean.TRUE; } URLConnection urlConnection = null; try { URL url = new URL(StringUtils.substringBefore(urlString, "#")); urlConnection = escapeIRI(url).openConnection(); urlConnection.setRequestProperty("Connection", "close"); urlConnection.setRequestProperty("User-Agent", userAgentHeader()); urlConnection.setIfModifiedSince(timestamp); int responseCode = ((HttpURLConnection) urlConnection).getResponseCode(); System.out.println(responseCode); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { return Boolean.FALSE; } else if (responseCode == HttpURLConnection.HTTP_OK) { return Boolean.TRUE; } else { // Return null to indicate if it's unclear whether the source has // been modified or not. return null; } } catch (IOException ioe) { return null; } finally { URLUtil.disconnect(urlConnection); } }
From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java
public static synchronized InputStream executeGet(HttpClient httpclient, HttpGet httpGet) throws ServiceFailure, NotFound, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidCredentials, InvalidRequest, AuthenticationTimeout, UnsupportedMetadataType, HttpException { InputStream response = null;//from ww w. j av a2 s . c o m try { HttpResponse httpResponse = httpclient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { HttpEntity resEntity = httpResponse.getEntity(); if (resEntity != null) { response = resEntity.getContent(); } else { throw new ServiceFailure("1002", "response code OK, but Entity not returned?" + httpResponse.toString()); } } else { HttpExceptionHandler.deserializeAndThrowException(httpResponse); } } catch (IOException ex) { throw new ServiceFailure("1002", ex.getMessage()); } return response; }
From source file:com.cd.reddit.http.RedditRequestor.java
private RedditRequestResponse readResponse(HttpURLConnection connection, RedditRequestInput input) throws RedditException { InputStream stream = null;//w w w. jav a2 s. c o m try { // Connection will be made here stream = connection.getInputStream(); // Buffers internally String responseBody = IOUtils.toString(stream, "UTF-8"); int statusCode = connection.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { throw new RedditException(generateErrorString(statusCode, input, responseBody)); } return new RedditRequestResponse(statusCode, responseBody); } catch (IOException e1) { throw new RedditException(e1); } finally { // Internally checks for null IOUtils.closeQuietly(stream); } }
From source file:com.cloud.maint.UpgradeManagerImpl.java
public String deployNewAgent(String url) { s_logger.info("Updating agent with binary from " + url); final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); int response; File file = null;// ww w .j a v a2s . co m try { response = client.executeMethod(method); if (response != HttpURLConnection.HTTP_OK) { s_logger.warn("Retrieving the agent gives response code: " + response); return "Retrieving the file from " + url + " got response code: " + response; } final InputStream is = method.getResponseBodyAsStream(); file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime())); file.deleteOnExit(); s_logger.debug("Retrieving new agent into " + file.getAbsolutePath()); final FileOutputStream fos = new FileOutputStream(file); final ByteBuffer buffer = ByteBuffer.allocate(2048); final ReadableByteChannel in = Channels.newChannel(is); final WritableByteChannel out = fos.getChannel(); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } in.close(); out.close(); s_logger.debug("New Agent zip file is now retrieved"); } catch (final HttpException e) { return "Unable to retrieve the file from " + url; } catch (final IOException e) { return "Unable to retrieve the file from " + url; } finally { method.releaseConnection(); } file.delete(); return "File will be deployed."; }
From source file:com.zaizi.sensefy.service.impl.SensefyServiceImpl.java
/** * Send a query to Sensefy.// ww w . ja v a 2s. c o m * * @param method the http method to use * @param url the url to call * @return the answer from the Sensefy server in a json-formatted string * @throws IOException when failing to properly query the Sensefy server */ private String querySensefy(String method, URL url) throws IOException { if (!RequestMethod.GET.toString().equals(method)) { // We only support GET requests for now throw new NotImplementedException(); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(RequestMethod.GET.toString()); try (InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return sb.toString(); } else { LOGGER.error("Failed to query Sensefy with the request: " + method + " " + url.toString() + ". Sensefy returned with the code " + conn.getResponseCode() + " and the message " + conn.getResponseMessage()); return null; } } }