List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:io.confluent.kafka.schemaregistry.client.rest.RestService.java
/** * @param requestUrl HTTP connection will be established with this url. * @param method HTTP method ("GET", "POST", "PUT", etc.) * @param requestBodyData Bytes to be sent in the request body. * @param requestProperties HTTP header properties. * @param responseFormat Expected format of the response to the HTTP request. * @param <T> The type of the deserialized response to the HTTP request. * @return The deserialized response to the HTTP request, or null if no data is expected. *//*from w w w . j av a2 s . c o m*/ private <T> T sendHttpRequest(String requestUrl, String method, byte[] requestBodyData, Map<String, String> requestProperties, TypeReference<T> responseFormat) throws IOException, RestClientException { log.debug(String.format("Sending %s with input %s to %s", method, requestBodyData == null ? "null" : new String(requestBodyData), requestUrl)); HttpURLConnection connection = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); // connection.getResponseCode() implicitly calls getInputStream, so always set to true. // On the other hand, leaving this out breaks nothing. connection.setDoInput(true); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } connection.setUseCaches(false); if (requestBodyData != null) { connection.setDoOutput(true); OutputStream os = null; try { os = connection.getOutputStream(); os.write(requestBodyData); os.flush(); } catch (IOException e) { log.error("Failed to send HTTP request to endpoint: " + url, e); throw e; } finally { if (os != null) os.close(); } } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); T result = jsonDeserializer.readValue(is, responseFormat); is.close(); return result; } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage; try { errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); } catch (JsonProcessingException e) { errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage()); } es.close(); throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode()); } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java
private String updateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null;//from w w w. ja v a2 s.c o m String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { URL url = new URL(fileUpdateUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", getMimeTypeFromFileName(fileName)); conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length)); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); LOG.debug("File updated : " + fileId); } catch (Exception e) { LOG.error("Could not update contents", e); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:com.intacct.ws.APISession.java
/** * You won't normally use this function, but if you just want to pass a fully constructed XML document * to Intacct, then use this function./* w w w. j a v a2 s .c om*/ * * @param String body a Valid XML string * @param String endPoint URL to post the XML to * * @throws exception * @return String the raw XML returned by Intacct */ public static String execute(String body, String endpoint) throws IOException { StringBuffer response = null; HttpURLConnection connection = null; // Create connection URL url = new URL(endpoint); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); /* wr.writeBytes ("fName=" + URLEncoder.encode("???", "UTF-8") + body + "&lName=" + URLEncoder.encode("???", "UTF-8")); */ wr.writeBytes("xmlrequest=" + URLEncoder.encode(body, "UTF-8")); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (connection != null) { connection.disconnect(); } return response.toString(); }
From source file:org.caboclo.clients.OneDriveClient.java
@Override public void putFile(File file, String path) throws IOException { final String BOUNDARY_STRING = "3i2ndDfv2rThIsIsPrOjEcTSYNceEMCPROTOTYPEfj3q2f"; //We use the directory name (without actual file name) to get folder ID int indDirName = path.replace("/", "\\").lastIndexOf("\\"); String targetFolderId = getFolderID(path.substring(0, indDirName)); System.out.printf("Put file: %s\tId: %s\n", path, targetFolderId); if (targetFolderId == null || targetFolderId.isEmpty()) { return;/*from w ww.ja v a 2 s .c o m*/ } URL connectURL = new URL("https://apis.live.net/v5.0/" + targetFolderId + "/files?" + "state=MyNewFileState&redirect_uri=https://login.live.com/oauth20_desktop.srf" + "&access_token=" + accessToken); HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_STRING); // set read & write conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); // set body DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes("--" + BOUNDARY_STRING + "\r\n"); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n"); dos.writeBytes("Content-Type: application/octet-stream\r\n"); dos.writeBytes("\r\n"); FileInputStream fileInputStream = new FileInputStream(file); int fileSize = fileInputStream.available(); int maxBufferSize = 8 * 1024; int bufferSize = Math.min(fileSize, maxBufferSize); byte[] buffer = new byte[bufferSize]; // send file int bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { // Upload file part(s) dos.write(buffer, 0, bytesRead); int bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, buffer.length); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } fileInputStream.close(); // send file end dos.writeBytes("\r\n"); dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n"); dos.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuilder sbuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { sbuilder.append(line); } String fileId = null; try { JSONObject json = new JSONObject(sbuilder.toString()); fileId = json.getString("id"); //System.out.println("File ID is: " + fileId); //System.out.println("File name is: " + json.getString("name")); //System.out.println("File uploaded sucessfully."); } catch (JSONException e) { Logger.getLogger(OneDriveClient.class.getName()).log(Level.WARNING, "Error uploading file " + file.getName(), e); } }
From source file:org.esupportail.twitter.services.OAuthTwitterApplicationOnlyService.java
public void afterPropertiesSet() throws Exception { HttpURLConnection connection = null; String encodedCredentials = encodeKeys(oAuthTwitterConfig.getConsumerKey(), oAuthTwitterConfig.getConsumerSecret()); try {// w ww. j a v a 2 s. c o m URL url = new URL(URL_TWITTER_OAUTH2_TOKEN); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Host", "api.twitter.com"); connection.setRequestProperty("User-Agent", ESUPTWITTER_USERAGENT); connection.setRequestProperty("Authorization", "Basic " + encodedCredentials); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.setRequestProperty("Content-Length", "29"); connection.setUseCaches(false); writeRequest(connection, "grant_type=client_credentials"); String jsonResponse = readResponse(connection); log.debug("jsonResponse of the bearer oauth request : " + jsonResponse); if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) { log.error( "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. Check values of Consumer Key and Consumer Secret in tokens.properties"); throw new RejectedAuthorizationException("", "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token"); } // Parse the JSON response into a JSON mapped object to fetch fields from. JSONObject obj = new JSONObject(jsonResponse); if (obj != null) { applicationOnlyBearerToken = (String) obj.get("access_token"); } } catch (MalformedURLException e) { throw new IOException("Invalid endpoint URL specified.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.jetbrains.webdemo.handlers.ServerHandler.java
private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response, Map<String, String> postParameters) { final boolean hasoutbody = (request.getMethod().equals("POST")); try {//from ww w. jav a2s . co m final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); final Enumeration<String> values = request.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); conn.addRequestProperty(header, value); } } conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setUseCaches(false); conn.setDoOutput(hasoutbody); if (postParameters != null && !postParameters.isEmpty()) { conn.setRequestMethod("POST"); try (OutputStream requestBody = conn.getOutputStream()) { boolean first = true; for (Map.Entry<String, String> entry : postParameters.entrySet()) { if (entry.getValue() == null) continue; if (first) { first = false; } else { requestBody.write('&'); } requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes()); requestBody.write('='); requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes()); } } } else { conn.setRequestMethod("GET"); } StringBuilder responseBody = new StringBuilder(); if (conn.getResponseCode() >= 400) { StringBuilder serverMessage = new StringBuilder(); try (InputStream errorStream = conn.getErrorStream()) { if (errorStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = errorStream.read(buffer); if (read <= 0) break; serverMessage.append(new String(buffer, 0, read)); } } } switch (conn.getResponseCode()) { case HttpServletResponse.SC_NOT_FOUND: responseBody.append("Kotlin compile server not found"); break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: responseBody.append("Kotlin compile server is temporary overloaded"); break; default: responseBody = serverMessage; break; } } else { try (InputStream inputStream = conn.getInputStream()) { if (inputStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = inputStream.read(buffer); if (read <= 0) break; responseBody.append(new String(buffer, 0, read)); } } } } writeResponse(request, response, responseBody.toString(), conn.getResponseCode()); } catch (SocketTimeoutException e) { writeResponse(request, response, "Compile server connection timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT); } catch (Exception e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "", "Can't forward request to Kotlin compile server"); writeResponse(request, response, "Can't send your request to Kotlin compile server", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:fyp.project.uploadFile.UploadFile.java
public int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;/*from w w w. jav a2 s. c om*/ DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 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("file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd); m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}", new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd }); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}", new Object[] { serverResponseMessage, serverResponseCode }); // close streams m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); } //this block will give the response of upload link return serverResponseCode; // like 200 (Ok) }
From source file:MegaHandler.java
private String api_request(String data) { HttpURLConnection connection = null; try {/* ww w . j a v a2 s . c o m*/ String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number; if (sid != null) urlString += "&sid=" + sid; URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); //use post method connection.setDoOutput(true); //we will send stuff connection.setDoInput(true); //we want feedback connection.setUseCaches(false); //no caches connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); try { OutputStreamWriter wr = new OutputStreamWriter(out); wr.write("[" + data + "]"); //data is JSON object containing the api commands wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the output stream if (out != null) out.close(); } InputStream in = connection.getInputStream(); StringBuffer response = new StringBuffer(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); //close the reader } catch (IOException e) { e.printStackTrace(); } finally { //in this case, we are ensured to close the input stream if (in != null) in.close(); } return response.toString().substring(1, response.toString().length() - 1); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:com.wavemaker.runtime.service.WaveMakerService.java
public String remoteRESTCall(String remoteURL, String params, String method, String contentType) { proxyCheck(remoteURL);/*from ww w . j a v a 2s .c om*/ String charset = "UTF-8"; StringBuffer returnString = new StringBuffer(); try { if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null || params.equals("")) { } else { if (remoteURL.indexOf("?") != -1) { remoteURL += "&" + params; } else { remoteURL += "?" + params; } } URL url = new URL(remoteURL); if (this.logger.isDebugEnabled()) { this.logger.debug("Opening URL: " + url); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(method); connection.setDoInput(true); connection.setRequestProperty("Accept-Charset", "application/json"); connection.setRequestProperty("Accept-Encoding", "text/plain"); connection.setRequestProperty("Content-Language", charset); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Transfer-Encoding", "identity"); connection.setUseCaches(false); HttpServletRequest request = RuntimeAccess.getInstance().getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> headers = request.getHeaders(name); if (headers != null && !name.toLowerCase().equals("accept-encoding") && !name.toLowerCase().equals("accept-charset") && !name.toLowerCase().equals("content-type")) { while (headers.hasMoreElements()) { String headerValue = headers.nextElement(); connection.setRequestProperty(name, headerValue); if (this.logger.isDebugEnabled()) { this.logger.debug("HEADER: " + name + ": " + headerValue); } } } } // Re-wrap single quotes into double quotes String finalParams; if (contentType.toLowerCase().equals("application/json")) { finalParams = params.replace("\'", "\""); if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null && !method.equals("")) { URLEncoder.encode(finalParams, charset); } } else { finalParams = params; } connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length)); // set payload if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null || method.equals("")) { DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.writeBytes(finalParams); writer.flush(); writer.close(); } InputStream response = connection.getInputStream(); BufferedReader reader = null; int responseLen = 0; try { int i = 0; String field; HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse(); while ((field = connection.getHeaderField(i)) != null) { String key = connection.getHeaderFieldKey(i); if (key == null || field == null) { } else { if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("transfer-encoding") && field.toLowerCase().equals("chunked")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("content-length")) { // do NOT use this length as return header value responseLen = new Integer(field); } else { wmResponse.addHeader(key, field); } } i++; } reader = new BufferedReader(new InputStreamReader(response, charset)); for (String line; (line = reader.readLine()) != null;) { returnString.append(line); } } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } connection.disconnect(); return returnString.toString(); } catch (Exception e) { logger.error("ERROR in XHR proxy call: " + e.getMessage()); throw new WMRuntimeException(e); } }
From source file:org.alfresco.repo.web.scripts.activities.SiteActivitySystemTest.java
private String callInOutWeb(String urlString, String method, String ticket, String data, String contentType, String soapAction) throws MalformedURLException, URISyntaxException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method);// w w w . j a v a2s . co m conn.setRequestProperty("Content-type", contentType); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); if (soapAction != null) { conn.setRequestProperty("SOAPAction", soapAction); } if (ticket != null) { // add Base64 encoded authorization header // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes())); } String result = null; BufferedReader br = null; DataOutputStream wr = null; OutputStream os = null; InputStream is = null; try { os = conn.getOutputStream(); wr = new DataOutputStream(os); wr.write(data.getBytes()); wr.flush(); } finally { if (wr != null) { wr.close(); } ; if (os != null) { os.close(); } ; } try { is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while (((line = br.readLine()) != null)) { sb.append(line); } result = sb.toString(); } finally { if (br != null) { br.close(); } ; if (is != null) { is.close(); } ; } return result; }