List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.bleum.canton.loadpage.LoadPage.java
private void readContentFromGet(String url) throws IOException { HttpURLConnection connection = null; BufferedReader reader = null; try {/*from w ww.j a v a 2s.c om*/ URL getUrl = new URL(url); connection = (HttpURLConnection) getUrl.openConnection(); connection.setUseCaches(false); connection.setRequestProperty("Cache-Control", "no-cache"); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((reader.readLine()) != null) { // System.out.println(lines); } } finally { IOUtils.closeQuietly(reader); if (connection != null) { connection.disconnect(); } } }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
public static Map<String, String> sendToServer(String epPostFix, Map<String, String> params, String option, Context context) throws IOException { String response = null;/* www . j a v a 2s. com*/ Map<String, String> response_params = new HashMap<String, String>(); String endpoint = CommonUtilities.SERVER_URL + epPostFix; SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); String ipSaved = mainPref.getString("ip", ""); if (ipSaved != null && ipSaved != "") { endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT + CommonUtilities.SERVER_APP_ENDPOINT + epPostFix; } URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; HttpsURLConnection sConn = null; try { if (url.getProtocol().toLowerCase().equals("https")) { sConn = (HttpsURLConnection) url.openConnection(); sConn = getTrustedConnection(context, sConn); sConn.setHostnameVerifier(WSO2MOBILE_HOST); conn = sConn; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod(option); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "close"); // post the request int status = 0; Log.v("Check verb", option); if (!option.equals("DELETE")) { OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response status = conn.getResponseCode(); Log.v("Response Status", status + ""); InputStream inStream = conn.getInputStream(); response = inputStreamAsString(inStream); response_params.put("response", response); Log.v("Response Message", response); response_params.put("status", String.valueOf(status)); } else { status = Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL); } if (status != Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL) && status != Integer.valueOf(CommonUtilities.REGISTERATION_SUCCESSFUL)) { throw new IOException("Post failed with error code " + status); } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (conn != null) { conn.disconnect(); } } return response_params; }
From source file:edu.pdx.cecs.orcycle.Uploader.java
private boolean uploadOneSegment(long currentNoteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {//from w w w. j a va 2 s.co m 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"); SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId); JSONObject json = segmentData.getJSON(); String deviceId = userId; DataOutputStream stream = new DataOutputStream(conn.getOutputStream()); stream.writeBytes(makeContentField("ratesegment", json.toString())); stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion))); stream.writeBytes(makeContentField("device", deviceId)); stream.writeBytes(contentFieldPrefix); stream.flush(); stream.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { segmentData.updateSegmentStatus(SegmentData.STATUS_SENT); result = true; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.vizury.PushNotification.Engine.Sender.java
/** * Makes an HTTP POST request to a given endpoint. * <p/>/* w w w .jav a 2s . com*/ * <p/> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * @return the underlying connection. * @throws java.io.IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warn("URL does not use https: " + url); } logger.debug("Sending POST to " + url); logger.debug("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; }
From source file:com.juick.android.Utils.java
public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) { try {/*from w ww.ja v a 2 s .co m*/ final String end = "\r\n"; final String twoHyphens = "--"; final String boundary = "****+++++******+++++++********"; URL apiUrl = new URL(url); final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setConnectTimeout(10000); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.connect(); OutputStream out = conn.getOutputStream(); PrintStream ps = new PrintStream(out); int index = 0; byte[] block = new byte[1024]; for (NameValuePair nameValuePair : data) { ps.print(twoHyphens + boundary + end); ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end); final InputStream value = nameValuePair.getValue(); while (true) { final int rd = value.read(block, 0, block.length); if (rd < 1) { break; } ps.write(block, 0, rd); } value.close(); ps.print(end); } ps.print(twoHyphens + boundary + twoHyphens + end); ps.close(); boolean b = conn.getResponseCode() == 200; if (!b) { return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false, null); } else { InputStream inputStream = conn.getInputStream(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; while (true) { int rd = inputStream.read(arr); if (rd < 1) break; baos.write(arr, 0, rd); } if (conn.getHeaderField("X-GZIPCompress") != null) { return new RESTResponse(null, false, baos.toString(0)); } else { return new RESTResponse(null, false, baos.toString()); } } finally { inputStream.close(); } } } catch (IOException e) { return new RESTResponse(e.toString(), false, null); } }
From source file:com.newrelic.agent.Obfuscation.Proguard.java
private void sendMapping(String mapping) /* */ {/*from w w w . ja v a2s. co m*/ /* 138 */ StringBuilder requestBody = new StringBuilder(); /* */ /* 140 */ requestBody.append("proguard=" + URLEncoder.encode(mapping)); /* 141 */ requestBody.append("&buildId=" + NewRelicClassVisitor.getBuildId()); /* */ try /* */ { /* 144 */ String host = "mobile-symbol-upload.newrelic.com"; /* 145 */ if (this.mappingApiHost != null) { /* 146 */ host = this.mappingApiHost; /* */ } /* */ /* 149 */ URL url = new URL("https://" + host + "/symbol"); /* 150 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /* */ /* 152 */ connection.setUseCaches(false); /* 153 */ connection.setDoOutput(true); /* 154 */ connection.setRequestMethod("POST"); /* 155 */ connection.setRequestProperty("X-APP-LICENSE-KEY", this.licenseKey); /* 156 */ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /* 157 */ connection.setRequestProperty("Content-Length", Integer.toString(requestBody.length())); /* */ /* 159 */ DataOutputStream request = new DataOutputStream(connection.getOutputStream()); /* 160 */ request.writeBytes(requestBody.toString()); /* 161 */ request.close(); /* */ /* 163 */ int responseCode = connection.getResponseCode(); /* 164 */ if (responseCode == 400) { /* 165 */ InputStream inputStream = connection.getErrorStream(); /* 166 */ String response = convertStreamToString(inputStream); /* 167 */ this.log .error("Unable to send your ProGuard mapping.txt to New Relic as the params are incorrect: " + response); /* 168 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* 169 */ } else if (responseCode > 400) { /* 170 */ InputStream inputStream = connection.getErrorStream(); /* 171 */ String response = convertStreamToString(inputStream); /* 172 */ this.log.error("Unable to send your ProGuard mapping.txt to New Relic - received status " + responseCode + ": " + response); /* 173 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ } /* */ /* 176 */ this.log.info("Successfully sent mapping.txt to New Relic."); /* */ /* 178 */ connection.disconnect(); /* */ } catch (IOException e) { /* 180 */ this.log.error("Encountered an error while uploading your ProGuard mapping to New Relic", e); /* 181 */ this.log .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually."); /* */ } /* */ }
From source file:jp.go.nict.langrid.servicecontainer.executor.jsonrpc.DynamicJsonRpcServiceExecutor.java
@Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { Map<String, Object> mimeHeaders = new HashMap<String, Object>(); final List<RpcHeader> rpcHeaders = new ArrayList<RpcHeader>(); Pair<Endpoint, Long> r = preprocessJsonRpc(mimeHeaders, rpcHeaders); Endpoint ep = r.getFirst();/* w w w . ja va 2 s . com*/ long s = System.currentTimeMillis(); HttpURLConnection con = null; JsonRpcResponse ret = null; RpcFault fault = null; try { con = (HttpURLConnection) ep.getAddress().toURL().openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(3000); con.setReadTimeout(10000); con.setRequestProperty("Accept", "application/json-rpc"); con.setRequestProperty("Content-type", "application/json-rpc"); con.setRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.JSON_RPC); String authUserName = ep.getUserName(); String authPassword = ep.getPassword(); if (authUserName != null && authUserName.length() > 0) { String header = authUserName + ":" + ((authPassword != null) ? authPassword : ""); con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(header.getBytes()))); } for (Map.Entry<String, Object> entry : mimeHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue().toString()); } OutputStream os = con.getOutputStream(); JSON.encode(JsonRpcUtil.createRequest(rpcHeaders, method, args), os); os.flush(); InputStream is = null; try { is = con.getInputStream(); } catch (IOException e) { is = con.getErrorStream(); } finally { if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); is = new DuplicatingInputStream(is, baos); try { ret = JSON.decode(is, JsonRpcResponse.class); } catch (JSONException e) { fault = new RpcFault("Server.userException", e.toString(), ExceptionUtil.getMessageWithStackTrace(e) + "\nsource: " + new String(baos.toByteArray(), "UTF-8")); } } else { throw new RuntimeException("failed to open response stream."); } } if (ret.getError() != null) { fault = ret.getError(); throw RpcFaultUtil.rpcFaultToThrowable(ret.getError()); } return converter.convert(ret.getResult(), method.getReturnType()); } finally { long dt = System.currentTimeMillis() - s; List<RpcHeader> resHeaders = null; if (ret != null && ret.getHeaders() != null) { resHeaders = Arrays.asList(ret.getHeaders()); } postprocessJsonRpc(r.getSecond(), dt, con, resHeaders, fault); if (con != null) con.disconnect(); } }
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>GET</code> method. * @param req servlet request//from ww w .j av a 2 s . com * @param resp servlet response */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read result headers of GET, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } InputStream in = con.getInputStream(); OutputStream out = resp.getOutputStream(); final byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.flush(); } catch (Exception e) { throw new ServletException(e); } }
From source file:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url// w w w . j av a 2s . com * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:org.mf.api.net.stack.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @return an open connection/*from ww w . ja va2 s. c om*/ */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); connection.setChunkedStreamingMode(0); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }