List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:org.cohorte.remote.dispatcher.servlet.ServletWrapper.java
@Override public void sendDiscovered(final String aHost, final int aPort, final String aPath) { // Prepare our endpoints final Collection<Map<String, Object>> endpointsMaps = new LinkedList<Map<String, Object>>(); for (final ExportEndpoint endpoint : pDispatcher.getEndpoints()) { endpointsMaps.add(endpoint.toMap()); }// w w w . j a v a 2s . co m // Convert the list to JSON final String data = new JSONArray(endpointsMaps).toString(); // Prepare the path to the servlet endpoints final StringBuilder servletPath = new StringBuilder(aPath); if (!aPath.endsWith("/")) { servletPath.append("/"); } servletPath.append("endpoints"); final URL url; try { url = new URL("http", aHost, aPort, servletPath.toString()); } catch (final MalformedURLException ex) { pLogger.log(LogService.LOG_ERROR, "Error forging URL to send a discovered packet: " + ex, ex); return; } // Send a POST request HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) url.openConnection(); // POST message httpConnection.setRequestMethod("POST"); httpConnection.setUseCaches(false); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); // Headers httpConnection.setRequestProperty("Content-Type", "application/json"); // After fields, before content httpConnection.connect(); // Write the event in the request body, if any final OutputStream outStream = httpConnection.getOutputStream(); try { outStream.write(data.getBytes()); outStream.flush(); } finally { // Always be nice... outStream.close(); } // Flush the request final int responseCode = httpConnection.getResponseCode(); final String responseData = new String(RSUtils.inputStreamToBytes(httpConnection.getInputStream())); if (responseCode != HttpURLConnection.HTTP_OK) { pLogger.log(LogService.LOG_WARNING, "Error sending a 'discovered' packet: " + responseCode + " - " + responseData); return; } } catch (final IOException ex) { pLogger.log(LogService.LOG_ERROR, "Error sending the 'discovered' packet: " + ex, ex); } finally { // Clean up if (httpConnection != null) { httpConnection.disconnect(); } } }
From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java
private void publish(IProject project, File zipFile) throws UnsupportedEncodingException, MalformedURLException, IOException, ProtocolException, FileNotFoundException, ParseException, CoreException { // FIXME What if user isn't signed in? We can enforce that they must be in enablement of action, but maybe the // sign-in timed out or something. ITitaniumUser user = TitaniumCorePlugin.getDefault().getUserManager().getSignedInUser(); Map<String, String> data = new HashMap<String, String>(); data.put("sid", user.getSessionID()); //$NON-NLS-1$ data.put("token", user.getToken()); //$NON-NLS-1$ data.put("uid", user.getUID()); //$NON-NLS-1$ data.put("uidt", user.getUIDT()); //$NON-NLS-1$ // Post zip to url URL postURL = makeURL(PUBLISH_URL, data); IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Request: {0}", postURL), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); HttpURLConnection con = (HttpURLConnection) postURL.openConnection(); con.setUseCaches(false); con.setDoOutput(true);//from w w w . j ava 2s .c om con.setRequestMethod("POST"); //$NON-NLS-1$ con.setRequestProperty("User-Agent", TitaniumConstants.USER_AGENT); //$NON-NLS-1$ // Pipe zip contents to stream OutputStream out = con.getOutputStream(); IOUtil.pipe(new BufferedInputStream(new FileInputStream(zipFile)), out); out.flush(); out.close(); // Force to finish, grab response code int code = con.getResponseCode(); // Delete the destDir after POST has finished if (!zipFile.delete()) { zipFile.deleteOnExit(); } // If the http code is 200 from POST, parse response as JSON. Else display error if (code == 200) { String responseText = IOUtil.read(con.getInputStream()); IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Response: {0}:{1}", code, responseText), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); Object result = new JSONParser().parse(responseText); if (result instanceof JSONObject) { JSONObject json = (JSONObject) result; boolean successful = (Boolean) json.get("success"); //$NON-NLS-1$ if (!successful) { // FIXME For some reason we're failing here but Titanium Developer isn't. Bad zip file? Maybe we're // piping it to stream incorrectly? throw new CoreException(new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code, (String) json.get("message"), null)); //$NON-NLS-1$ } // run pollPackagingRequest with "ticket" from JSON and project GUID if 200 and reports success pollPackagingRequest(project, (String) json.get("ticket")); //$NON-NLS-1$ } } else { String responseText = IOUtil.read(con.getErrorStream()); IdeLog.logError(DesktopPlugin.getDefault(), MessageFormat.format("API Response: {0}:{1}.", code, responseText), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); throw new CoreException(new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code, Messages.Packager_PackagingFailedHTTPError + code, null)); } }
From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java
private IStatus invokeCloudService(URL baseURL, Map<String, String> data, String type) { DataOutputStream outputStream = null; try {/*from w ww . ja va 2 s . co m*/ if (type == null) { type = "POST"; //$NON-NLS-1$ } if (data == null) { data = new HashMap<String, String>(); } // always pass MID data.put("mid", TitaniumCorePlugin.getMID()); //$NON-NLS-1$ ITitaniumUser user = TitaniumCorePlugin.getDefault().getUserManager().getSignedInUser(); data.put("sid", user.getSessionID()); //$NON-NLS-1$ data.put("token", user.getToken()); //$NON-NLS-1$ data.put("uid", user.getUID()); //$NON-NLS-1$ data.put("uidt", user.getUIDT()); //$NON-NLS-1$ // If this is not a POST, append query params don't put as data in body! if (!"POST".equals(type)) //$NON-NLS-1$ { baseURL = makeURL(baseURL.toString(), data); } HttpURLConnection con = (HttpURLConnection) baseURL.openConnection(); con.setUseCaches(false); con.setRequestMethod(type); con.setRequestProperty("User-Agent", TitaniumConstants.USER_AGENT); //$NON-NLS-1$ if ("POST".equals(type)) //$NON-NLS-1$ { con.setDoOutput(true); // Write the data to the connection outputStream = new DataOutputStream(con.getOutputStream()); outputStream.writeBytes(getQueryString(data)); outputStream.flush(); } IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Request: {0}", baseURL), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); // Force to finish, grab response code int code = con.getResponseCode(); // If the http code is 200 from POST, parse response as JSON. Else display error if (code == 200) { String responseText = IOUtil.read(con.getInputStream()); IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Response: {0}:{1}", code, responseText), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); return new Status(IStatus.OK, DesktopPlugin.PLUGIN_ID, code, responseText, null); } // TODO Read from connection to populate message! return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code, null, null); } catch (Exception e) { return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0, e.getMessage(), e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // ignores the exception } } } }
From source file:com.seeyon.apps.m1.common.manager.menu.impl.MMenuManagerImpl.java
/** * ?HttpURLConnection?//w ww . j av a 2 s . com * * @param in * @param urlPath * @param cookies * @return * @throws Exception */ private int getNum(String urlPath) { if (urlPath == null || urlPath.length() < 10) { return 0; } HttpURLConnection httpURLConnection = null; String resulet = ""; try { URL url = new URL(urlPath);// ??? httpURLConnection = (HttpURLConnection) url.openConnection(); // ? httpURLConnection.setDoOutput(true);// httpURLConnection.setRequestMethod("get");// ?? httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); httpURLConnection.setDoInput(true);// ? httpURLConnection.setConnectTimeout(40000); // httpURLConnection.setReadTimeout(40000);// ? httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { InputStream in = httpURLConnection.getInputStream(); byte[] b = new byte[1024]; int lent = 0; while ((lent = in.read(b)) != -1) { resulet = resulet + new String(b, 0, lent); } in.close(); } return Integer.valueOf(resulet); } catch (Exception e) { e.printStackTrace(); } finally { httpURLConnection.disconnect(); } return 0; }
From source file:io.confluent.kafkarest.tools.ConsumerPerformance.java
private <T> T request(String target, String method, byte[] entity, String entityLength, TypeReference<T> responseFormat) { HttpURLConnection connection = null; try {/*from w w w . j av a 2 s . co m*/ URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); if (entity != null) { connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT); connection.setRequestProperty("Content-Length", entityLength); } connection.setDoInput(true); connection.setUseCaches(false); if (entity != null) { connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(entity); os.flush(); os.close(); } int responseStatus = connection.getResponseCode(); if (responseStatus >= 400) { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); es.close(); throw new RuntimeException(String.format("Unexpected HTTP error status %d for %s request to %s: %s", responseStatus, method, target, errorMessage.getMessage())); } if (responseStatus != HttpURLConnection.HTTP_NO_CONTENT) { InputStream is = connection.getInputStream(); T result = serializer.readValue(is, responseFormat); is.close(); return result; } return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private HttpURLConnection openConnection(String uri, String method) { for (String host : hosts) { try {//from w w w . ja v a2 s. c o m URL templateUrl = new URL("http://" + host + uri); HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection(); connection.setRequestMethod(method); connection.setConnectTimeout(timeout); connection.setUseCaches(false); if ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) { connection.setDoOutput(true); } connection.connect(); return connection; } catch (IOException e) { LOGGER.error("Error connecting to {}: {}", host, e); } } throw new ElasticsearchConnectionException( "Error connecting to elasticsearch host(s): " + Arrays.toString(hosts)); }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
private HttpURLConnection buildConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true);/*from w w w . ja v a 2 s .com*/ connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setUseCaches(false); // Set the authorization header if one has been specified if (authorization != null) { connection.setRequestProperty("Authorization", authorization); } return connection; }
From source file:edu.pdx.cecs.orcycle.NoteUploader.java
boolean uploadOneNote(long noteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/* ww w. ja va2 s.c o m*/ JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId); URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonNote; if (null != (jsonNote = getNoteJSON(noteId))) { try { String deviceId = userId; dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n"); dos.writeBytes( notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n"); if (null != imageData) { dos.writeBytes(notesep + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n"); dos.write(imageData); dos.writeBytes("\r\n"); } dos.writeBytes(notesep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } else { result = false; } } catch (IllegalStateException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (IOException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (JSONException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { NoteUploader.setPending(noteId, false); } return result; }
From source file:com.juhnowski.sanskrvar.Main.java
public Entry checkWord(String word) { StringBuilder sb = new StringBuilder(); sb.append("http://www.sanskrit-lexicon.uni-koeln.de/scans/WILScan/2014/web/webtc/getword.php?key="); sb.append(word);// ww w.j ava2 s . c o m sb.append("&filter=roman&noLit=off&transLit=hk"); String targetURL = sb.toString(); String urlParameters = ""; HttpURLConnection connection = null; try { //Create connection URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/xhr"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); String s = response.toString(); if (!s.contains("<h2>not found:")) { return new Entry(word, s); } else { return null; } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:AIR.Common.Web.HttpWebHelper.java
public String getResponse(String urlString, String postRequestParams, String contentMimeType) throws Exception { try {/* w w w . ja v a 2 s . c o m*/ URL url = new URL(urlString); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Content-Type", String.format("application/%s; charset=UTF-8", contentMimeType)); urlConn.setUseCaches(false); // the request will return a response urlConn.setDoInput(true); // set request method to POST urlConn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream()); writer.write(postRequestParams); writer.flush(); // reads response, store line by line in an array of Strings BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuffer bfr = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { bfr.append(line + "\n"); } reader.close(); writer.close(); urlConn.disconnect(); return bfr.toString(); } catch (Exception exp) { StringWriter strn = new StringWriter(); exp.printStackTrace(new PrintWriter(strn)); _logger.error(strn.toString()); exp.printStackTrace(); throw new Exception(exp); } }