List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:core.Annotator.java
private String makeHttpRequest(List<Variant> variants) { final JSONObject message = getJsonMessage(variants); final String server = "http://grch37.rest.ensembl.org/vep/human/region"; final String postBody = message.toString(); try {/*from w w w. j ava 2 s. c o m*/ final URL url = new URL(server); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/json"); httpConnection.setRequestProperty("Accept", "application/json"); httpConnection.setRequestProperty("Content-Length", Integer.toString(postBody.getBytes().length)); httpConnection.setUseCaches(false); httpConnection.setDoOutput(true); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(httpConnection.getOutputStream()))) { writer.write(postBody); } final int responseCode = httpConnection.getResponseCode(); if (responseCode != 200) { println("VEP service unavailable"); throw new RuntimeException("Response code was not 200. Detected response was " + responseCode); } try (BufferedReader reader = new BufferedReader( new InputStreamReader(httpConnection.getInputStream()))) { final StringBuilder builder = new StringBuilder(); reader.lines().forEach(builder::append); // System.out.println(builder.toString()); return builder.toString(); } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.codehaus.mojo.tomcat.TomcatManager.java
/** * Invokes Tomcat manager with the specified command and content data. * // w w w. jav a2 s . com * @param path the Tomcat manager command to invoke * @param data an input stream to the content data * @return the Tomcat manager response * @throws TomcatManagerException if the Tomcat manager request fails * @throws IOException if an i/o error occurs */ protected String invoke(String path, InputStream data) throws TomcatManagerException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url + path).openConnection(); connection.setAllowUserInteraction(false); connection.setDoInput(true); connection.setUseCaches(false); if (data == null) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else { connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/octet-stream"); } if (userAgent != null) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Authorization", toAuthorization(username, password)); connection.connect(); if (data != null) { pipe(data, connection.getOutputStream()); } String response = toString(connection.getInputStream(), MANAGER_CHARSET); if (!response.startsWith("OK -")) { throw new TomcatManagerException(response); } return response; }
From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java
public boolean performRequest() { jsonResponseArray = null;//from www . ja v a2 s . c o m jsonResponseObject = null; HttpURLConnection connection = null; try { // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP. mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject()); byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8"); URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(mRequestMethod); connection.setUseCaches(false); // For all methods except GET we need to include data in the body. if (mRequestMethod != "GET") { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length)); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postDataBytes); wr.flush(); wr.close(); } if (connection.getResponseCode() == 200) { InputStreamReader in = new InputStreamReader((InputStream) connection.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine().toString(); buff.close(); Object json = new JSONTokener(line).nextValue(); if (json.getClass() == JSONObject.class) { jsonResponseObject = (JSONObject) json; } else if (json.getClass() == JSONArray.class) { jsonResponseArray = (JSONArray) json; } // else members will be left to null indicating no valid response. return true; } } catch (MalformedURLException e) { Log.e(TAG, e.getMessage()); } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } return false; }
From source file:CloudManagerAPI.java
private HttpURLConnection openConnection(final URL url, final Method method) throws IOException { // open the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // use supplied method and configure the connection connection.setRequestMethod(method.toString()); connection.setDoInput(true);/* ww w . j a v a 2 s .c om*/ connection.setDoOutput(true); connection.setUseCaches(false); // set the request headers connection.setRequestProperty(HEADER_KEY_TOKEN, token); connection.setRequestProperty(HEADER_KEY_VERSION, "" + version); return connection; }
From source file:core.AbstractTest.java
private HttpURLConnection getHttpConnection(String sUrl, String sMethod) { URL uri = null;// w ww . jav a 2s. c o m HttpURLConnection conn = null; try { uri = new URL(sUrl); conn = (HttpURLConnection) uri.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(sMethod); // POST, PUT, DELETE, GET conn.setUseCaches(false); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("Connection", "Keep-Alive"); //conn.setConnectTimeout(60000); //60 secs //conn.setReadTimeout(60000); //60 secs //conn.setRequestProperty("Accept-Encoding", "UTF-8"); } catch (Exception e) { Assert.fail("Unable to get HttpConnection " + e.getMessage()); } return conn; }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Opens a connection to the POST end point specified in the mConf * {@link HttpConfiguration} and sends the content of mEntity. Attempts to * read the answer from the server after the POST Request. * // w w w . j a v a 2 s . com * @param mConf The {@link HttpConfiguration} of the request. * @param mEntity The Entity to send in the HTTP Post. Should be built using * {@link #_buildEntity}. * * @return The result of the HTTP Post request. Either #SUCCESS, * #FAILURE_CONNECTION, #FAILURE_TRANSFER, #FAILURE_RESPONSE, * #FAILURE_MALFORMEDURL. * * @see HttpConfiguration * @see _ProgressiveEntity */ protected Long _httpPost(HttpConfiguration mConf, _ProgressiveEntity mEntity) { Log.d("HttpPoster", String.format("_httpPost: Entering Instance %d", _iInstanceId)); /******** Open request ********/ try { HttpURLConnection mConn = (HttpURLConnection) mConf.getEndPoint().openConnection(); mConn.setRequestMethod("POST"); mConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + mConf.getHTTPBoundary()); mConn.setDoInput(true); mConn.setDoOutput(true); mConn.setUseCaches(false); mConn.setReadTimeout(mConf.getReadTimeout()); mConn.setConnectTimeout(mConf.getConnectTimeout()); mConn.setInstanceFollowRedirects(false); mConn.connect(); Log.d("HttpPoster", String.format("_httpPost: Connected for Instance %d", _iInstanceId)); try { /********** Write request ********/ _dispatchOnStartTransfer(); Log.d("HttpPoster", String.format("_httpPost: Sending for Instance %d", _iInstanceId)); mEntity.writeTo(mConn.getOutputStream()); mConn.getOutputStream().flush(); mConn.getOutputStream().close(); _iResponseCode = mConn.getResponseCode(); try { Log.d("HttpPoster", String.format("_httpPost: Reading for Instance %d", _iInstanceId)); _readServerAnswer(mConn.getInputStream()); return SUCCESS; } catch (IOException e) { return FAILURE_RESPONSE; } } catch (Exception e) { Log.d("HTTPParser", e.getMessage()); e.printStackTrace(); return FAILURE_TRANSFER; } finally { if (mConn != null) { Log.d("HttpPoster", String.format("_httpPost: Disconnecting Instance %d", _iInstanceId)); mConn.disconnect(); } } } catch (Exception e) { return FAILURE_CONNECTION; } }
From source file:calliope.db.CouchConnection.java
/** * Get a document's revid/*from w w w. ja v a 2 s. com*/ * @param db the database name * @param docID a prepared docID * @return a string or null to indicate it isn't there */ private String getRevId(String db, String docID) throws AeseException { HttpURLConnection conn = null; try { String login = (user == null) ? "" : user + ":" + password + "@"; URL u = new URL("http://" + login + host + ":" + dbPort + "/" + db + "/" + docID); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("HEAD"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); //Get Response String revid = conn.getHeaderField("ETag"); if (revid != null) revid = revid.replaceAll("\"", ""); conn.disconnect(); return revid; } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }
From source file:com.docdoku.client.actions.MainController.java
private void performHeadHTTPMethod(String pURL) throws MalformedURLException, IOException { MainModel model = MainModel.getInstance(); URL url = new URL(pURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(true);//from www . j a v a 2s . c o m conn.setRequestProperty("Connection", "Keep-Alive"); byte[] encoded = org.apache.commons.codec.binary.Base64 .encodeBase64((model.getLogin() + ":" + model.getPassword()).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); conn.setRequestMethod("HEAD"); conn.connect(); int code = conn.getResponseCode(); System.out.println("Head HTTP response code: " + code); }
From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java
public String executePost(String postdata) throws HttpSessionException { URL url;/*w w w .java 2 s .c o m*/ HttpURLConnection connection = null; try { //Create connection url = new URL(this.uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); connection.setRequestProperty("User-Agent", "java"); if (!this.user.isEmpty() && !this.password.isEmpty()) { String authString = this.user + ":" + this.password; String authStringEnc = Base64.encodeBytes(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postdata); wr.flush(); wr.close(); //Get Response 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(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new HttpSessionException("Server returned: " + connection.getResponseMessage()); } return response.toString(); } catch (Exception e) { throw new HttpSessionException(e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.norconex.committer.idol.IdolCommitter.java
/** * Creates a HTTP URL connection with the proper Post method and properties. * @param url the URL to open/* www . jav a 2 s.co m*/ * @return HttpUrlConnection object */ private HttpURLConnection createURLConnection(String url) { URL targetURL; HttpURLConnection con = null; try { targetURL = new URL(url); con = (HttpURLConnection) targetURL.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // add request header con.setRequestMethod("POST"); } catch (MalformedURLException e) { LOG.error("Something went wrong with the URL: " + url, e); } catch (IOException e) { LOG.error("I got an I/O problem trying to connect to the server", e); } return con; }