List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:crow.weibo.util.WeiboUtil.java
public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException { OutputStream os;// w ww.j a v a2 s .co m List<PostParameter> dataparams = new ArrayList<PostParameter>(); for (PostParameter key : params) { if (key.isFile()) { dataparams.add(key); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); ByteArrayBuffer buff = new ByteArrayBuffer(1000); for (PostParameter p : params) { byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8"); buff.append(arr, 0, arr.length); } String end = "--" + BOUNDARY + "--" + "\r\n"; byte[] endArr = end.getBytes(); buff.append(endArr, 0, endArr.length); conn.setRequestProperty("Content-Length", buff.length() + ""); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(buff.toByteArray()); buff.clear(); os.flush(); String response = ""; response = Util.inputStreamToString(conn.getInputStream()); return response; }
From source file:com.gmobi.poponews.util.HttpHelper.java
private static Response doRequest(String url, Object raw, int method) { disableSslCheck();/* ww w. j ava 2 s. co m*/ boolean isJson = raw instanceof JSONObject; String body = raw == null ? null : raw.toString(); Response response = new Response(); HttpURLConnection connection = null; try { URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (method == HTTP_POST) connection.setRequestMethod("POST"); if (body != null) { if (isJson) { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); } OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(body); osw.flush(); osw.close(); } InputStream in = connection.getInputStream(); response.setBody(FileHelper.readText(in, "UTF-8")); response.setStatusCode(connection.getResponseCode()); in.close(); connection.disconnect(); connection = null; } catch (Exception e) { Logger.error(e); try { if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) { response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8")); } } catch (Exception ex) { Logger.error(ex); } } return response; }
From source file:com.codelanx.codelanxlib.logging.Debugger.java
/** * Sends a JSON payload to a URL specified by the string parameter * //from www.j a va 2 s. co m * @since 0.1.0 * @version 0.1.0 * * @param url The URL to report to * @param payload The JSON payload to send via POST * @throws IOException If the sending failed */ private static void send(String url, JSONObject payload) throws IOException { URL loc = new URL(url); HttpURLConnection http = (HttpURLConnection) loc.openConnection(); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json"); http.setUseCaches(false); http.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) { wr.writeBytes(payload.toJSONString()); wr.flush(); } }
From source file:gribbit.util.RequestBuilder.java
/** * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true, * returns a byte[] array, otherwise returns the response as a String. *//*from w w w . j av a 2s. c o m*/ private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse, int redirDepth) { if (redirDepth > 6) { throw new IllegalArgumentException("Too many redirects"); } HttpURLConnection connection = null; try { // Add the URL query params if this is a GET request String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url; connection = (HttpURLConnection) new URL(reqURL).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(isGET ? "GET" : "POST"); connection.setUseCaches(false); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/43.0.2357.125 Safari/537.36"); if (!isGET) { // Send the body if this is a POST request connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String params = WebUtils.buildQueryString(keyValuePairs); connection.setRequestProperty("Content-Length", Integer.toString(params.length())); try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) { w.writeBytes(params); w.flush(); } } if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) { // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET. return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */ true, isBinaryResponse, redirDepth + 1); } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) { // For 200 OK, return the text of the response if (isBinaryResponse) { ByteArrayOutputStream output = new ByteArrayOutputStream(32768); IOUtils.copy(connection.getInputStream(), output); return output.toByteArray(); } else { StringWriter writer = new StringWriter(1024); IOUtils.copy(connection.getInputStream(), writer, "UTF-8"); return writer.toString(); } } else { throw new IllegalArgumentException( "Got non-OK HTTP response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new IllegalArgumentException( "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception e) { } } } }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {/*from ww w . j a v a 2 s . co m*/ // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:org.bibsonomy.util.WebUtils.java
/** * Returns the cookies returned by the server on accessing the URL. * The format of the returned cookies is as * /* w ww. j a v a 2 s. c o m*/ * * @param url * @return The cookies as string, build by {@link #buildCookieString(List)}. * @throws IOException */ public static String getCookies(final URL url) throws IOException { final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE); urlConn.connect(); final List<String> cookies = urlConn.getHeaderFields().get("Set-Cookie"); urlConn.disconnect(); return buildCookieString(cookies); }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * /* w ww .j av a 2 s . co m*/ * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.jooketechnologies.network.ServerUtilities.java
static JSONObject post(String endpoint, int action, Map<String, String> params) { URL url;//from w ww . j a v a2 s. c o m 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(); // constructs the POST body using the parameters 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(); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); InputStream is = conn.getInputStream(); if (status != 200) { if (conn != null) { conn.disconnect(); } } else { JSONObject jsonObject = streamToString(is); return jsonObject; } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:Main.java
@TargetApi(Build.VERSION_CODES.KITKAT) public static String net(String strUrl, Map<String, Object> params, String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null;/*from w w w .j ava 2 s .c o m*/ try { StringBuffer sb = new StringBuffer(); if (method == null || method.equals("GET")) { strUrl = strUrl + "?" + urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if (method == null || method.equals("GET")) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params != null && method.equals("POST")) { try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(urlencode(params)); } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); String strRead = null; while ((strRead = reader.readLine()) != null) { sb.append(strRead); } rs = sb.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } return rs; }
From source file:org.bibsonomy.util.WebUtils.java
/** * Do a POST request to the given URL with the given content. Assume the charset of the result to be charset. * //from w w w . j av a 2s . c o m * @param url * @param postContent * @param charset - the assumed charset of the result. If <code>null</code>, the charset from the response header is used. * @param cookie - the Cookie to be attached to the request. If <code>null</code>, the Cookie header is not set. * @return The content of the result page. * * @throws IOException * * @Deprecated */ public static String getPostContentAsString(final URL url, final String postContent, final String charset, final String cookie) throws IOException { final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty(CONTENT_TYPE_HEADER_NAME, "application/x-www-form-urlencoded"); /* * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some * pages require it to download content. */ urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE); if (cookie != null) { urlConn.setRequestProperty(COOKIE_HEADER_NAME, cookie); } writeStringToStream(postContent, urlConn.getOutputStream()); // connect urlConn.connect(); /* * extract character encoding from header */ final String activeCharset; if (charset == null) { activeCharset = getCharset(urlConn); } else { activeCharset = charset; } /* * FIXME: check content type header to ensure that we only read textual * content (and not a PDF, radio stream or DVD image ...) */ // write into string writer final StringBuilder out = inputStreamToStringBuilder(urlConn.getInputStream(), activeCharset); // disconnect urlConn.disconnect(); return out.toString(); }