List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title, String description, boolean retry) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);// ww w .j a va2 s. c o m urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); // urlConnection.setRequestProperty("Content-Length", newValue); urlConnection.setRequestProperty("Slug", filePath); String atomData = null; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; String template = readFile(activity, R.raw.gdata).toString(); // Workarounds for corner cases. Youtube doesnt like empty titles if (title == null || title.length() == 0) { title = "Untitled"; } if (description == null || description.length() == 0) { description = "No description"; } atomData = String.format(template, title, description, category, this.tags); OutputStreamWriter outStreamWriter = null; int responseCode = -1; try { outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); /* * urlConnection.connect(); InputStream is = * urlConnection.getInputStream(); BufferedReader in = new * BufferedReader(new InputStreamReader(is)); String inputLine; * * while ((inputLine = in.readLine()) != null) { * Log.d(TAG,inputLine); } in.close(); */ responseCode = urlConnection.getResponseCode(); // ERROR LOGGING InputStream is = urlConnection.getErrorStream(); if (is != null) { Log.e(TAG, " Error stream from Youtube available!"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) { Log.d(TAG, inputLine); } in.close(); Map<String, List<String>> hfs = urlConnection.getHeaderFields(); for (Entry<String, List<String>> hf : hfs.entrySet()) { Log.d(TAG, " entry : " + hf.getKey()); List<String> vals = hf.getValue(); for (String s : vals) { Log.d(TAG, "vals:" + s); } } } } catch (IOException e) { // // Catch IO Exceptions here, like UnknownHostException, so we can // detect network failures, and send a notification // Log.d(TAG, " Error occured in uploadMetaData! "); e.printStackTrace(); responseCode = -1; outStreamWriter = null; // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); // forward it on! throw e; } if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(activity, handler, filePath, title, description, false); } else { // Probably not authorised! // Need to setup a Youtube account. // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
@Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { try {/*from www . ja v a 2s . c o m*/ final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer); String expandedUrl = formatter.format(url); String querystring = ""; if (!params.isEmpty()) { querystring = params.entrySet().stream().map( e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue())) .collect(Collectors.joining("&")); expandedUrl = expandedUrl.concat("?").concat(querystring); } StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ") .append(expandedUrl); URL requestUrl = new URL(expandedUrl); HttpURLConnection httpURLConnection; if (truststorePath != null && expandedUrl.startsWith("https://")) { httpURLConnection = openSecureConnection(requestUrl); } else { httpURLConnection = (HttpURLConnection) requestUrl.openConnection(); } callDump.append("\n ").append("Method: " + method); callDump.append("\n ").append("Connection timeout: " + connectionTimeout); callDump.append("\n ").append("Read timeout: " + readTimeout); httpURLConnection.setRequestMethod(method); httpURLConnection.setConnectTimeout(connectionTimeout); httpURLConnection.setReadTimeout(readTimeout); for (Entry<String, String> header : headers.entrySet()) { String k = formatter.format(header.getKey()); String v = formatter.format(header.getValue()); httpURLConnection.setRequestProperty(k, v); callDump.append("\n ").append("Header: " + k + "=" + v); if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) { body = querystring; } } if (sendGVBufferObject && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length)); callDump.append("\n ").append("Content-Length: " + requestData.length); callDump.append("\n ").append("Request body: binary"); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(requestData); dataOutputStream.flush(); dataOutputStream.close(); } else if (Objects.nonNull(body) && body.length() > 0) { String expandedBody = formatter.format(body); callDump.append("\n ").append("Request body: " + expandedBody); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(expandedBody); outputStreamWriter.flush(); outputStreamWriter.close(); } httpURLConnection.connect(); InputStream responseStream = null; try { httpURLConnection.getResponseCode(); responseStream = httpURLConnection.getInputStream(); } catch (IOException connectionFail) { responseStream = httpURLConnection.getErrorStream(); } for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) { if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) { gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()), header.getValue().stream().collect(Collectors.joining(";"))); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { // No content gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode())); gvBuffer.setProperty(RESPONSE_MESSAGE, Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL")); httpURLConnection.disconnect(); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }
From source file:com.google.ytd.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 {/*from w w w . j a v a 2s.c om*/ 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")); 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()); 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); 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)); 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:it.govpay.core.utils.client.BasicClient.java
private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl) throws ClientException { // Creazione Connessione int responseCode; HttpURLConnection connection = null; byte[] msg = null; GpContext ctx = GpThreadLocal.get(); String urlString = url.toExternalForm(); if (isAzioneInUrl) { if (!urlString.endsWith("/")) urlString = urlString.concat("/"); try {/*from w ww .j a va 2s . c o m*/ url = new URL(urlString.concat(azione)); } catch (MalformedURLException e) { throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e); } } try { Message requestMsg = new Message(); requestMsg.setType(MessageType.REQUEST_OUT); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (soap) { connection.setRequestProperty("SOAPAction", "\"" + azione + "\""); requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\"")); } requestMsg.setContentType("text/xml"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestMethod("POST"); // Imposta Contesto SSL se attivo if (sslContext != null) { HttpsURLConnection httpsConn = (HttpsURLConnection) connection; httpsConn.setSSLSocketFactory(sslContext.getSocketFactory()); HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled(); httpsConn.setHostnameVerifier(disabilitato); } // Imposta l'autenticazione HTTP Basic se attiva if (ishttpBasicEnabled) { Base64 base = new Base64(); String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoding); requestMsg.addHeader(new Property("Authorization", "Basic " + encoding)); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (soap) { SOAPUtils.writeMessage(body, header, baos); } else { JaxbUtils.marshal(body, baos); } ctx.getIntegrationCtx().setMsg(baos.toByteArray()); invokeOutHandlers(); if (log.getLevel().isMoreSpecificThan(Level.TRACE)) { StringBuffer sb = new StringBuffer(); for (String key : connection.getRequestProperties().keySet()) { sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key)); } sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg())); log.trace(sb.toString()); } requestMsg.setContent(ctx.getIntegrationCtx().getMsg()); ctx.getContext().getRequest().setOutDate(new Date()); ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length)); ctx.log(requestMsg); connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg()); } catch (Exception e) { throw new ClientException(e); } try { responseCode = connection.getResponseCode(); ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode)); } catch (Exception e) { throw new ClientException(e); } Message responseMsg = new Message(); responseMsg.setType(MessageType.RESPONSE_IN); for (String key : connection.getHeaderFields().keySet()) { if (connection.getHeaderFields().get(key) != null) { if (key == null) responseMsg .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0))); else if (connection.getHeaderFields().get(key).size() == 1) responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0))); else responseMsg.addHeader( new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key)))); } } try { if (responseCode < 300) { try { if (connection.getInputStream() == null) { return null; } msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream()) : new byte[] {}; if (msg.length > 0) responseMsg.setContent(msg); return msg; } catch (Exception e) { throw new ClientException("Messaggio di risposta non valido", e); } } else { try { msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream()) : new byte[] {}; responseMsg.setContent(msg); } catch (IOException e) { msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes(); } finally { log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode + "]\nRisposta: " + new String(msg)); } throw new ClientException("Ricevuto [HTTP " + responseCode + "]"); } } finally { if (responseMsg != null) { ctx.getContext().getResponse().setInDate(new Date()); ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length); ctx.log(responseMsg); } if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null && connection.getHeaderFields() != null) { StringBuffer sb = new StringBuffer(); for (String key : connection.getHeaderFields().keySet()) { sb.append("\n\t" + key + ": " + connection.getHeaderField(key)); } sb.append("\n" + new String(msg)); log.trace(sb.toString()); } } }
From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java
public Boolean upload_v2() { this.downloader.login(); String page = this.downloader.getUrlData(this.URL); String viewstate = ""; Pattern p = Pattern// w ww. j a v a2 s . c o m .compile("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"([^\"]+)\" />"); Matcher m = p.matcher(page); m.find(); viewstate = m.group(1); //System.out.println("viewstate=" + viewstate); // got viewstate InputStream fn_is = null; String raw_upload_data = ""; try { fn_is = new ByteArrayInputStream( ("GC2BNHP,2010-11-07T14:00Z,Write note,\"bla bla\"").getBytes("UTF-8")); raw_upload_data = "GC2BNHP,2010-11-07T20:50Z,Write note,\"bla bla\"".getBytes("UTF-8").toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String cookies_string = this.downloader.getCookies(); ArrayList<InputStream> files = new ArrayList(); files.add(fn_is); Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht.put("__VIEWSTATE", viewstate); HttpData data = HttpRequest.post(this.URL, ht, files, cookies_string); //System.out.println(data.content); String boundary = "----------ThIs_Is_tHe_bouNdaRY_$"; String crlf = "\r\n"; URL url = null; try { url = new URL(this.URL); } catch (MalformedURLException e2) { e2.printStackTrace(); } HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException e2) { e2.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); try { con.setRequestMethod("POST"); } catch (java.net.ProtocolException e) { e.printStackTrace(); } con.setRequestProperty("Cookie", cookies_string); //System.out.println("Cookie: " + cookies_string[0] + "=" + cookies_string[1]); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"); con.setRequestProperty("Pragma", "no-cache"); //con.setRequestProperty("Connection", "Keep-Alive"); String content_type = String.format("multipart/form-data; boundary=%s", boundary); con.setRequestProperty("Content-Type", content_type); DataOutputStream dos = null; try { dos = new DataOutputStream(con.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } String raw_data = ""; // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$btnUpload") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "Upload Field Note" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$chkSuppressDate") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "__VIEWSTATE") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + viewstate + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", "ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt") + crlf; raw_data = raw_data + String.format("Content-Type: %s", "text/plain") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + raw_upload_data + crlf; // // raw_data = raw_data + "--" + boundary + "--" + crlf; raw_data = raw_data + crlf; try { this.SendPost(this.URL, raw_data, cookies_string); } catch (IOException e1) { e1.printStackTrace(); } //System.out.println(raw_data); try { dos.writeBytes(raw_data); //dos.writeChars(raw_data); dos.flush(); } catch (IOException e) { e.printStackTrace(); } HttpData ret2 = new HttpData(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(con.getInputStream()), HTMLDownloader.large_buffer_size); String line; while ((line = rd.readLine()) != null) { ret2.content += line + "\r\n"; } } catch (IOException e) { e.printStackTrace(); } //get headers Map<String, List<String>> headers = con.getHeaderFields(); Set<Entry<String, List<String>>> hKeys = headers.entrySet(); for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) { Entry<String, List<String>> m99 = i.next(); //System.out.println("HEADER_KEY" + m99.getKey() + "=" + m99.getValue()); ret2.headers.put(m99.getKey(), m99.getValue().toString()); if (m99.getKey().equals("set-cookie")) ret2.cookies.put(m99.getKey(), m99.getValue().toString()); } try { dos.close(); rd.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println(ret2.content); //System.out.println("FFFFFFFFFFFFFFFFFFFFFFFFFFFF"); ClientHttpRequest client_req; try { client_req = new ClientHttpRequest(this.URL); String[] cookies_string2 = this.downloader.getCookies2(); for (int jk = 0; jk < cookies_string2.length; jk++) { System.out.println(cookies_string2[jk * 2] + "=" + cookies_string2[(jk * 2) + 1]); client_req.setCookie(cookies_string2[jk * 2], cookies_string2[(jk * 2) + 1]); } client_req.setParameter("ctl00$ContentBody$btnUpload", "Upload Field Note"); client_req.setParameter("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt", fn_is); InputStream response = client_req.post(); //System.out.println(this.convertStreamToString(response)); } catch (IOException e) { e.printStackTrace(); } //ArrayList<InputStream> files = new ArrayList(); files.clear(); files.add(fn_is); Hashtable<String, String> ht2 = new Hashtable<String, String>(); ht2.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht2.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht2.put("__VIEWSTATE", viewstate); HttpData data3 = HttpRequest.post(this.URL, ht2, files, cookies_string); //System.out.println(data3.content); // String the_page2 = this.downloader.get_reader_mpf(this.URL, raw_data, null, true, boundary); //System.out.println("page2=\n" + the_page2); Boolean ret = false; return ret; }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.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(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {// w ww.j a v a 2 s. c o m urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(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); // /XXX hardcoded video mimetype urlConnection.setRequestProperty("Content-Type", "video/mp4"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(TAG, 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(TAG, String.format( * "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, * totalBytesUploaded, percent)); */ if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(TAG, "responseCode=" + responseCode); Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); Log.i(TAG, "Youtube video submitted - new video id is " + videoId); // 100% finished here. // dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(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(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 successfully Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(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:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title, String description, boolean retry, long sdrecord_id) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);/*from w w w . ja v a 2 s . co m*/ urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); // urlConnection.setRequestProperty("Content-Length", newValue); urlConnection.setRequestProperty("Slug", filePath); String atomData = null; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; String template = readFile(activity, R.raw.gdata).toString(); // Workarounds for corner cases. Youtube doesnt like empty titles if (title == null || title.length() == 0) { title = "Untitled"; } if (description == null || description.length() == 0) { description = "No description"; } // Check user preference to see if YouTube videos should be private by // default. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true); String private_or_not = "<yt:private />"; if (!ytPrivate) { private_or_not = ""; } atomData = String.format(template, title, description, category, this.tags, private_or_not); OutputStreamWriter outStreamWriter = null; int responseCode = -1; try { outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); /* * urlConnection.connect(); InputStream is = * urlConnection.getInputStream(); BufferedReader in = new * BufferedReader(new InputStreamReader(is)); String inputLine; * * while ((inputLine = in.readLine()) != null) { * Log.d(TAG,inputLine); } in.close(); */ responseCode = urlConnection.getResponseCode(); // ERROR LOGGING InputStream is = urlConnection.getErrorStream(); if (is != null) { Log.e(TAG, " Error stream from Youtube available!"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) { Log.d(TAG, inputLine); } in.close(); Map<String, List<String>> hfs = urlConnection.getHeaderFields(); for (Entry<String, List<String>> hf : hfs.entrySet()) { Log.d(TAG, " entry : " + hf.getKey()); List<String> vals = hf.getValue(); for (String s : vals) { Log.d(TAG, "vals:" + s); } } } } catch (IOException e) { // // Catch IO Exceptions here, like UnknownHostException, so we can // detect network failures, and send a notification // Log.d(TAG, " Error occured in uploadMetaData! "); e.printStackTrace(); responseCode = -1; outStreamWriter = null; mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); // forward it on! throw e; } if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(activity, handler, filePath, title, description, false, sdrecord_id); } else { mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT); // Probably not authorised! // Need to setup a Youtube account. // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }
From source file:com.orange.datavenue.client.common.ApiInvoker.java
public HttpResponse invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws SDKException, HTTPException { System.out.println("invokeAPI()"); System.out.println(String.format("host : %1$s", host)); System.out.println(String.format("path : %1$s", path)); System.out.println(String.format("method : %1$s", method)); System.out.println(String.format("contentType : %1$s", contentType)); HttpResponse response = new HttpResponse(); StringBuilder paramsBuilder = new StringBuilder(); for (String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null) { if (paramsBuilder.toString().length() == 0) paramsBuilder.append("?"); else//from ww w.j a v a 2 s .c o m paramsBuilder.append("&"); paramsBuilder.append(escapeString(key)).append("=").append(escapeString(value)); } } String query = paramsBuilder.toString(); //System.out.println( String.format("query : %1$s", query)); //System.out.println( String.format("body : %1$s", (String)body)); HttpURLConnection urlConnection = null; try { URL url = new URL(String.format("%1$s%2$s%3$s", host, path, query)); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); for (String key : headerParams.keySet()) { urlConnection.setRequestProperty(key, headerParams.get(key)); } urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-Type", contentType); if (body != null) { urlConnection.setDoOutput(true); } if ("GET".equals(method)) { if (body != null) { writeStream(urlConnection.getOutputStream(), serialize(body)); } response.body = readStream(urlConnection.getInputStream()); System.out.println(String.format("response : %1$s", response.body)); } else if ("POST".equals(method)) { if (body != null) { writeStream(urlConnection.getOutputStream(), serialize(body)); } response.body = readStream(urlConnection.getInputStream()); System.out.println(String.format("response : %1$s", response.body)); } else if ("PUT".equals(method)) { if ("application/x-www-form-urlencoded".equals(contentType)) { StringBuilder formParamBuilder = new StringBuilder(); // encode the form params for (String key : formParams.keySet()) { String value = formParams.get(key); if (value != null && !"".equals(value.trim())) { if (formParamBuilder.length() > 0) { formParamBuilder.append("&"); } try { formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=") .append(URLEncoder.encode(value, "utf8")); } catch (Exception e) { // move on to next System.out.println(e.toString()); } } } writeStream(urlConnection.getOutputStream(), formParamBuilder.toString()); } else { writeStream(urlConnection.getOutputStream(), serialize(body)); } response.body = readStream(urlConnection.getInputStream()); System.out.println(String.format("response : %1$s", response)); } else if ("DELETE".equals(method)) { if (body != null) { writeStream(urlConnection.getOutputStream(), serialize(body)); } response.body = readStream(urlConnection.getInputStream()); System.out.println(String.format("response : %1$s", response)); } else if ("OPTIONS".equals(method)) { System.out.println("method not implemented"); throw new SDKException(500, String.format("method not implemented %1$s", method)); } else if ("HEAD".equals(method)) { System.out.println("method not implemented"); throw new SDKException(500, String.format("method not implemented %1$s", method)); } else if ("TRACE".equals(method)) { System.out.println("method not implemented"); throw new SDKException(500, String.format("method not implemented %1$s", method)); } else { System.out.println("Unknown method"); throw new SDKException(500, String.format("method not implemented %1$s", method)); } response.headers = urlConnection.getHeaderFields(); } catch (MalformedURLException e) { System.out.println(e.toString()); } catch (IOException e) { // When an IOException occured, we have to read on the ErrorStream if (urlConnection != null) { try { int code = urlConnection.getResponseCode(); String json = readStream(urlConnection.getErrorStream()); try { JSONObject jsonObject = new JSONObject(json); int datavenueCode = 0; if (jsonObject.has("code")) { datavenueCode = jsonObject.getInt("code"); } String datavenueMessage = ""; if (jsonObject.has("message")) { datavenueMessage = jsonObject.getString("message"); } String datavenueDescription = ""; if (jsonObject.has("description")) { datavenueDescription = jsonObject.getString("description"); } DatavenueError datavenueError = new DatavenueError(); datavenueError.setCode(datavenueCode); datavenueError.setMessage(datavenueMessage); datavenueError.setDescription(datavenueDescription); throw new HTTPException(code, datavenueError); } catch (JSONException je) { System.out.println(je.toString()); } } catch (IOException io) { System.out.println(io.toString()); throw new SDKException(500, io.toString(), io); } } else { System.out.println(e.toString()); throw new SDKException(500, e.toString(), e); } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } response.log(); return response; }
From source file:study.tdcc.act.MainCalendar.java
/** * XML?????/*from w ww . j a v a 2 s . c om*/ * * @param strUrl * @param strXml * @param strMethod (PUT,DELETE) * @return InputStream ???InputStream */ public InputStream httpPostXml(String strUrl, String strXml, String strMethod) { Log.d("DEBUG", "MainCalendar httpPostXml Start"); blHttpSucceeded = false; try { while (strUrl != null) { URL urlObj = new URL(strUrl); //URL????? HttpURLConnection httpURLCObj = (HttpURLConnection) urlObj.openConnection(); //?POST? httpURLCObj.setRequestMethod("POST"); //GData-Version? httpURLCObj.setRequestProperty(GDATA_VERSION_TAG, GDATA_VERSION); if (strMethod != null) { //POST??????If-Match:*?X-HTTP-Method-Override httpURLCObj.setRequestProperty("If-Match", "*"); httpURLCObj.setRequestProperty("X-HTTP-Method-Override", strMethod); } // httpURLCObj.setDoOutput(true); //Content-Type??XML httpURLCObj.setRequestProperty("Content-Type", CONTENT_TYPE_AA); // httpURLCObj.setUseCaches(false); //OutputStreamWriter??XML?? OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLCObj.getOutputStream(), "UTF-8"); outputStreamWriter.write(strXml); outputStreamWriter.close(); //HTTP?? intResponseCode = 0; intResponseCode = httpURLCObj.getResponseCode(); strUrl = null; Log.d("DEBUG", "MainCalendar httpPostXml HttpResponseCode : " + intResponseCode); if (intResponseCode == HttpURLConnection.HTTP_OK || intResponseCode == HttpURLConnection.HTTP_CREATED) { //??OK???CREATED????? blHttpSucceeded = true; Log.d("DEBUG", "MainCalendar httpPostXml End(1)"); //?InputStream?? return httpURLCObj.getInputStream(); } else if (intResponseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //??MOVED_TEMP????????? //?Location????URL????(?while? Map<String, List<String>> mResponseHeaders = httpURLCObj.getHeaderFields(); if (mResponseHeaders.containsKey("Location")) { strUrl = mResponseHeaders.get("Location").get(0); } else if (mResponseHeaders.containsKey("location")) { strUrl = mResponseHeaders.get("location").get(0); } } else { //??OK???CREATED???MOVED_TEMP?? blHttpSucceeded = false; Log.d("DEBUG", "MainCalendar httpPostXml End(2) ??OK,CREATED,MOVED_TEMP??"); } } } catch (Exception e) { Log.e("ERROR", "MainCalendar httpPostXml ERROR", e); } Log.d("DEBUG", "MainCalendar httpPostXml End(3)"); return null; }
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
private String gdataUpload(File file, String uploadUrl, int start, int end, Activity activity) throws IOException { mActivity = activity;// www.j a va2s . co m 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(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else { urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(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); // /XXX hardcoded video mimetype urlConnection.setRequestProperty("Content-Type", "video/mp4"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(TAG, urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; Thread thread = new Thread() { public void run() { int lastPercent = 0; while (lastPercent < 100) { if (lastPercent != percentUploaded) { ((SSCXferActivity) mActivity).showProgress("uploading...", percentUploaded); lastPercent = percentUploaded; } try { Thread.sleep(1000); } catch (Exception e) { } } } }; thread.start(); while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; percentUploaded = (int) (((float) totalBytesUploaded) / ((float) currentFileSize) * 99f); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(TAG, "responseCode=" + responseCode); Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); Log.i(TAG, "Youtube video submitted - new video id is " + videoId); // 100% finished here. // dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(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(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 successfully Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(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; }