List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java
/** * {@inheritDoc}// ww w.j a va 2 s . co m */ @Override public WebResponse getResponse(final WebRequest webRequest) throws IOException { final long startTime = System.currentTimeMillis(); final URL url = webRequest.getUrl(); if (LOG.isTraceEnabled()) { LOG.trace("about to fetch URL " + url); } // hack for JS, about, and data URLs. final WebResponse response = produceWebResponseForGAEProcolHack(url); if (response != null) { return response; } // this is a "normal" URL try { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setUseCaches(false); connection.setConnectTimeout(webClient_.getOptions().getTimeout()); connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent()); connection.setInstanceFollowRedirects(false); // copy the headers from WebRequestSettings for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } addCookies(connection); final HttpMethod httpMethod = webRequest.getHttpMethod(); connection.setRequestMethod(httpMethod.name()); if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) { connection.setDoOutput(true); final String charset = webRequest.getCharset(); connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName()); try (final OutputStream outputStream = connection.getOutputStream()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); outputStream.write(query.getBytes(charset)); if (webRequest.getRequestBody() != null) { IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream); } } } final int responseCode = connection.getResponseCode(); if (LOG.isTraceEnabled()) { LOG.trace("fetched URL " + url); } final List<NameValuePair> headers = new ArrayList<>(); for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) { final String headerKey = headerEntry.getKey(); if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK") final StringBuilder sb = new StringBuilder(); for (final String headerValue : headerEntry.getValue()) { if (sb.length() != 0) { sb.append(", "); } sb.append(headerValue); } headers.add(new NameValuePair(headerKey, sb.toString())); } } final byte[] byteArray; try (final InputStream is = responseCode < 400 ? connection.getInputStream() : connection.getErrorStream()) { byteArray = IOUtils.toByteArray(is); } final long duration = System.currentTimeMillis() - startTime; final WebResponseData responseData = new WebResponseData(byteArray, responseCode, connection.getResponseMessage(), headers); saveCookies(url.getHost(), headers); return new WebResponse(responseData, webRequest, duration); } catch (final IOException e) { LOG.error("Exception while tyring to fetch " + url, e); throw new RuntimeException(e); } }
From source file:com.sandklef.coachapp.http.HttpAccess.java
public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName) throws HttpAccessException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; DataInputStream inputStream = null; String pathToOurFile = fileName; String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.UPLOAD_PATH;/*from w ww . j a va 2 s . c om*/ Log.d(LOG_TAG, "Upload server url: " + urlServer); Log.d(LOG_TAG, "Upload file: " + fileName); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); Log.d(LOG_TAG, "connection: " + connection + " uploading data to video: " + videoUuid); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod(HttpSettings.HTTP_POST); // int timeout = LocalStorage.getInstance().getnetworkTimeout(); Log.d(LOG_TAG, "timeout: " + timeout); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken()); connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub()); connection.setRequestProperty("Connection", "close"); Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties()); outputStream = new DataOutputStream(connection.getOutputStream()); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { Log.d(LOG_TAG, " writing data to stream (" + bytesRead + " / " + bytesAvailable + ")"); outputStream.write(buffer, 0, bufferSize); Log.d(LOG_TAG, " writing data to stream -"); bytesAvailable = fileInputStream.available(); Log.d(LOG_TAG, " writing data to stream -"); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.flush(); outputStream.close(); // Responses from the server (code and message) fileInputStream.close(); int serverResponseCode = 0; long before = System.currentTimeMillis(); try { Log.d(LOG_TAG, " ... writing done, getting response code"); serverResponseCode = connection.getResponseCode(); Log.d(LOG_TAG, " ... writing done, getting response message"); String serverResponseMessage = connection.getResponseMessage(); Log.d(LOG_TAG, "ServerCode:" + serverResponseCode); Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage); } catch (java.net.SocketTimeoutException e) { Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace"); e.printStackTrace(); throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW); } long after = System.currentTimeMillis(); long diff = after - before; Log.d(LOG_TAG, "diff: " + diff + "ms " + diff / 1000 + "s"); if (diff > LocalStorage.getInstance().getnetworkTimeout()) { throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW); } if (serverResponseCode >= 409) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.CONFLICT_ERROR); } if (serverResponseCode < 500 && serverResponseCode >= 400) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.ACCESS_ERROR); } try { Log.d(LOG_TAG, " ... disconnecting"); connection.disconnect(); } catch (Exception e) { Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace"); e.printStackTrace(); } }
From source file:fr.cls.atoll.motu.api.rest.MotuRequest.java
/** * Excute de la requte et retourne du rsultat dans un flux. Le flux contient le fichier netcdf en * mode console, l'url du fichier extrait en mode url ou l'url du fichier de status en mode status (ce * fichier contiendra l'tat de la requte en cours : INPRGRESS ou ERROR msg_erreur ou DONE. * /*from ww w. ja v a 2 s.com*/ * @return le flux rsultat de la requte * * @throws MotuRequestException the motu request exception * @deprecated use {@link #executeV2()} * */ @Deprecated public InputStream execute() throws MotuRequestException { if (LOG.isDebugEnabled()) { LOG.debug("execute() - entering"); } String requestParams = null; try { requestParams = getRequestParams(); } catch (UnsupportedEncodingException ex) { LOG.error("execute()", ex); throw new MotuRequestException("Request parameters encoding error", ex); } URL url = null; Map<String, String> requestExtraInfo = MotuRequest.searchUrlUserPwd(servletUrl); String targetUrl = servletUrl; if (requestExtraInfo != null) { targetUrl = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_MODE_URL); } try { url = new URL(targetUrl); } catch (MalformedURLException ex) { LOG.error("execute()", ex); throw new MotuRequestException("Invalid url", ex); } LOG.info("URL=" + getRequestUrl()); HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(connectTimeout); } catch (IOException ex) { LOG.error("execute()", ex); throw new MotuRequestException("Request connection failed", ex); } try { // Effectue un POST Http plutt qu'un GET car le nombre de // paramtres peu tre important et on ne veut pas voir passer // le login et password dans l'url if (requestExtraInfo != null) { String user = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_LOGIN); String pwd = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_PWD); if ((user != null) && (pwd != null)) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(user); stringBuffer.append(":"); stringBuffer.append(pwd); byte[] encoding = new org.apache.commons.codec.binary.Base64() .encode(stringBuffer.toString().getBytes()); urlConnection.setRequestProperty("Authorization", "Basic " + new String(encoding)); } } urlConnection.setDoOutput(true); Writer writer = new OutputStreamWriter(urlConnection.getOutputStream()); try { writer.write(requestParams); writer.flush(); } finally { IOUtils.closeQuietly(writer); } InputStream returnInputStream = urlConnection.getInputStream(); if (LOG.isDebugEnabled()) { LOG.debug("execute() - exiting"); } return returnInputStream; } catch (IOException ex) { LOG.error("execute()", ex); MotuRequestException motuRequestException; try { motuRequestException = new MotuRequestException("Request failed - errorCode: " + urlConnection.getResponseCode() + ", errorMsg: " + urlConnection.getResponseMessage(), ex); } catch (IOException e) { LOG.error("execute()", e); motuRequestException = new MotuRequestException("Request connection failed", ex); } throw motuRequestException; } }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/* w ww.j a v a2s. co m*/ URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }
From source file:JavaTron.AudioTron.java
/** * Method to execute a POST Request to the Audiotron - JSC * //from ww w . j a v a 2 s .c om * @param address - The requested page * @param args - The POST data * @param parser - A Parser Object fit for parsing the response * * @return null on success, a string on error. The string describes * the error. * * @throws IOException */ protected String post(String address, Vector args, Parser parser) throws IOException { String ret = null; URL url; HttpURLConnection conn; String formData = new String(); // Build the POST data for (int i = 0; i < args.size(); i += 2) { if (showPost) { System.out.print("POST: " + args.get(i).toString() + " = "); System.out.println(args.get(i + 1).toString()); } formData += URLEncoder.encode(args.get(i).toString(), "UTF-8") + "=" + URLEncoder.encode(args.get(i + 1).toString(), "UTF-8"); if (i + 2 != args.size()) formData += "&"; } // Build the connection Headers and POST the data try { url = new URL("http://" + getServer() + address); if (showAddress || showPost) { System.out.println("POST: " + address); System.out.println("POST: " + formData); } conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", USER_AGENT); // Authorization header String auth = getUsername() + ":" + getPassword(); conn.setRequestProperty("Authorization", "Basic " + B64Encode(auth.getBytes())); // Debug if (showAuth) { System.out.println("POST: AUTH: " + auth); } conn.setRequestProperty("Content Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "" + Integer.toString(formData.getBytes().length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); // Send the request to the audiotron DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(formData); wr.flush(); wr.close(); // Process the Response if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) { try { ret = conn.getResponseMessage(); } catch (IOException ioe) { ioe.printStackTrace(); } if (ret == null) { ret = "Unknown Error"; } if (parser != null) { parser.begin(ret); } return ret; } isr = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(isr); String s; getBuffer = new StringBuffer(); if (parser != null) { parser.begin(null); } while ((s = reader.readLine()) != null) { if (showGet) { System.out.println(s); } getBuffer.append(s); getBuffer.append("\n"); if (parser == null) { // getBuffer.append(s); } else { if (!parser.parse(s)) { return "Parse Error"; } } } if (parser == null && showUnparsedOutput) { System.out.println(getBuffer); } if (parser != null) { parser.end(false); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { // if this happens, call the parse method if there is a parser // with a null value to indicate an error if (parser != null) { parser.end(true); } throw (ioe); } finally { try { isr.close(); } catch (Exception e) { // this is ok } } return ret; }
From source file:org.miloss.fgsms.bueller.Bueller.java
/** * Sends an HTTP GET request to a url//from w w w . j a v a2 s . c o m * * @param endpoint - The URL of the server. (Example: " * http://www.yahoo.com/search") Note: This method will add the question * mark (?wsdl) to the request * @return - OK for 200 messages, all others, the actually response code or * error message */ protected String sendGetRequest(boolean pooled, String endpoint, int depth) { if (depth > 10) { //abort, possible redirect loop return "Aborting due to redirect loop"; } String result = null; String policyUrl = new String(endpoint); if (endpoint.startsWith("http://")) { // Send a GET request to the servlet HttpURLConnection conn = null; try { String originalendpoint = endpoint; if (!endpoint.endsWith("?wsdl")) { endpoint = endpoint + "?wsdl"; } conn = (HttpURLConnection) new URL(endpoint).openConnection(); if (conn.getResponseCode() == 401) { //basic example WWW-Authenticate: Basic realm="fgsms Services" //digest example WWW-Authenticate: Digest realm="fgsms Services", qop="auth", nonce="2569aa2af54f6d47e8472f47f2e3da01", opaque="a39d25cce80574f8255b97052d8f1544" //WWW-Authenticate: Negotiate //WWW-Authenticate: NTLM // String authtype = conn.getHeaderField("WWW-Authenticate"); // if (authtype.toLowerCase().startsWith("digest")) { return sendGetRequestAuth(pooled, endpoint, policyUrl, depth + 1); } else if (conn.getResponseCode() == 404) { //fix for sonatype nexus and non wsdl urls conn = (HttpURLConnection) new URL(originalendpoint).openConnection(); return "Not found"; } else if (conn.getResponseCode() == HttpStatus.SC_MOVED_PERMANENTLY || conn.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY || conn.getResponseCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { //follow the redirect String newUrl = conn.getHeaderField("Location"); return sendGetRequest(pooled, newUrl, depth + 1); //System.out.println("Moved to " + newUrl); //should be the new destination url //return "Moved " + conn.getResponseMessage(); } else if (conn.getResponseCode() == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } InputStream inputStream = null; try { inputStream = conn.getInputStream(); byte[] buffer = new byte[1024]; while (inputStream.read(buffer) >= 0) { } inputStream.close(); } catch (Exception f) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception ex) { } } } String msg = conn.getResponseMessage(); conn.disconnect(); return msg; } catch (java.net.UnknownHostException ex) { return "Host unknown"; } catch (Exception ex) { return ex.getMessage(); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception ex) { } } } } else if (endpoint.startsWith("https://")) { if (!endpoint.endsWith("?wsdl")) { endpoint = endpoint + "?wsdl"; } DefaultHttpClient c = new DefaultHttpClient(); try { URL url = new URL(endpoint); int port = url.getPort(); if (port == -1 && endpoint.toLowerCase().startsWith("http:")) { port = 80; } if (port == -1 && endpoint.toLowerCase().startsWith("https:")) { port = 443; } Scheme sch = null; if (sfpki == null) { sch = new Scheme("https", port, sf); } else { sch = new Scheme("https", port, sfpki); } if (endpoint.toLowerCase().startsWith("https:")) { c.getConnectionManager().getSchemeRegistry().register(sch); } HttpGet m = new HttpGet(endpoint); HttpResponse res = c.execute(m); int status = res.getStatusLine().getStatusCode(); try { InputStream content = res.getEntity().getContent(); byte[] buffer = new byte[1024]; while (content.read(buffer) >= 0) { } } catch (Exception f) { } c.getConnectionManager().shutdown(); if (status == 401) { return sendGetRequestAuth(pooled, endpoint, policyUrl, depth + 1); } else if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT) { String newUrl = res.getHeaders("Location")[0].getValue(); return sendGetRequest(pooled, newUrl, depth + 1); } else if (status == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } else { return (status < 300) ? "OK" : "offline"; } } catch (Exception ex) { c.getConnectionManager().shutdown(); log.log(Level.WARN, "error caught connecting to " + endpoint, ex); return ex.getMessage(); } } else if (endpoint.startsWith("jms:")) { return doJmsURL(pooled, endpoint); } return "Unknown protocol"; }
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 w w w .ja 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:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;//from ww w. j av a2 s . c o m URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); Object o = null; if (progress != null) { o = progress.get(); } Progress p = null; if (o != null) { p = new Progress(o); } for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue(), p); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if (code < 200 || code >= 300) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:com.BeatYourRecord.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {// w w w .j a v a2s . c o m urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); //////may be //log.v("id man id",urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); //log.v("Video ID", videoId); vidId = videoId; String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); //log.v("10video id",videoId); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); //////////////may be for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:com.etalio.android.EtalioBase.java
protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename) throws ParseException, IOException, EtalioHttpException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try {/* www .j av a 2 s. co m*/ URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken()); connection.setRequestProperty("User-Agent", getEtalioUserAgent()); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + filename + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); if (connection.getResponseCode() > 300) { result = convertStreamToString(connection.getErrorStream()); } else { result = this.convertStreamToString(inputStream); } fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(), e.getMessage()); } }