List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.example.rartonne.appftur.HomeActivity.java
public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null;// ww w . j a va 2 s . c o m String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { //dialog.dismiss(); Log.e("uploadFile", "Source File not exist"); runOnUiThread(new Runnable() { public void run() { //messageText.setText("Source File not exist :"+uploadFilePath + "" + uploadFileName); } }); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { runOnUiThread(new Runnable() { public void run() { /*String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" +" http://www.androidexample.com/media/uploads/" +uploadFileName;*/ //messageText.setText(msg); /*Toast.makeText(getApplicationContext(), "File Upload Complete.", Toast.LENGTH_SHORT).show();*/ } }); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { //dialog.dismiss(); ex.printStackTrace(); runOnUiThread(new Runnable() { public void run() { //messageText.setText("MalformedURLException Exception : check script url."); /*Toast.makeText(getApplicationContext(), "MalformedURLException", Toast.LENGTH_SHORT).show();*/ } }); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { //dialog.dismiss(); e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { //messageText.setText("Got Exception : see logcat "); /*Toast.makeText(getApplicationContext(), "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();*/ } }); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } // dialog.dismiss(); return serverResponseCode; } // End else block }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public int uploadFile(String sourceFileUri) { String upLoadServerUri = ""; upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php"; String fileName = sourceFileUri; Log.d("file upload url", upLoadServerUri); HttpURLConnection conn = null; DataOutputStream dos = null;/* w w w .ja v a 2 s . com*/ String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.d("uploadFile", "Source File Does not exist"); return 0; } int serverResponseCode = 0; try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); //close the streams // fileInputStream.close(); dos.flush(); dos.close(); Log.d("Contact file ", "uploaded"); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; }
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 w w.ja va2s . 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:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate./*from www . j a va2s. c om*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry = -1; // Start with -1 so tries at least once, and retries at most MAX_CONN_RETRIES times for (; retry < MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try disconnection again conn.disconnect(); } setUseKeepAlive(false); } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection again // We don't want to continue using this connection, even if KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection again disconnect(conn); // Disconnect unless using KeepAlive } }
From source file:iracing.webapi.IracingWebApi.java
private SendPrivateMessageResult sendPrivateMessage(int customerDefinitionType, String customer, String subject, String message) throws IOException, LoginException { if (!cookieMap.containsKey(JSESSIONID)) { if (login() != LoginResponse.Success) return SendPrivateMessageResult.UNABLE_TO_LOGIN; }/*w ww .j a v a 2s .c om*/ SendPrivateMessageResult output = SendPrivateMessageResult.UNKNOWN_ERROR; if (!cookieMap.containsKey(JFORUMSESSIONID)) { if (!forumLoginAndGetCookie()) return SendPrivateMessageResult.UNABLE_TO_LOGIN; } try { // Make a connection URL url = new URL(FORUM_POST_PAGE_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //multipart/form-data conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); //conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY); conn.addRequestProperty(COOKIE, cookie); StringBuilder data = new StringBuilder(); // set the multipart form data parameters addMultipartFormData(data, "action", "sendSave"); addMultipartFormData(data, "module", "pm"); addMultipartFormData(data, "preview", "0"); addMultipartFormData(data, "start", null); if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_ID) { addMultipartFormData(data, "toUsername", null); addMultipartFormData(data, "toUserId", customer); } else if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_NAME) { addMultipartFormData(data, "toUsername", customer); addMultipartFormData(data, "toUserId", null); } addMultipartFormData(data, "disa1ble_html", "on"); addMultipartFormData(data, "attach_sig", "on"); addMultipartFormData(data, "subject", subject); addMultipartFormData(data, "message", message); addMultipartFormData(data, "addbbcode24", "#444444"); addMultipartFormData(data, "addbbcode26", "12"); addMultipartFormData(data, "helpbox", "Italic Text: [i]Text[/i] (alt+i)"); data.append(twoHyphens).append(BOUNDRY).append(twoHyphens); DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream()); try { dataOS.writeBytes(data.toString()); dataOS.flush(); } finally { dataOS.close(); } conn.connect(); if (isMaintenancePage(conn)) return SendPrivateMessageResult.UNABLE_TO_LOGIN; // Ensure we got the HTTP 200 response code int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new Exception(String.format("Received the response code %d from the URL %s : %s", responseCode, url, conn.getResponseMessage())); } String response = getResponseText(conn); // System.out.println(response); if (response.contains("Your message was successfully sent.")) { output = SendPrivateMessageResult.SUCCESS; } else if (response.contains( "Could not determine the user id. Please check if you typed the username correctly and try again.")) { output = SendPrivateMessageResult.USER_NOT_FOUND; } else if (response.contains( "Sorry, but this users inbox is currently full and cannot receive private messages at this time.")) { output = SendPrivateMessageResult.MAILBOX_FULL; } conn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } return output; }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;/*from ww w .ja va2 s. c om*/ BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI();// w w w . ja v a 2 s. c o m // Is this a CONNECT request? if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) { response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE???? handleConnect(pathInContext, pathParams, request, response); return; } try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) sendForbid(request, response, uri); return; } if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); 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.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warn(e.toString()); LogSupport.ignore(log, e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request); } }
From source file:dj.comprobantes.offline.service.CPanelServiceImp.java
@Override public boolean guardarComprobanteNube(Comprobante comprobante) throws GenericException { boolean guardo = true; UtilitarioCeo utilitario = new UtilitarioCeo(); Map<String, Object> params = new LinkedHashMap<>(); params.put("NOMBRE_USUARIO", comprobante.getCliente().getNombreCliente()); params.put("IDENTIFICACION_USUARIO", comprobante.getCliente().getIdentificacion()); params.put("CORREO_USUARIO", comprobante.getCliente().getCorreo()); params.put("CODIGO_ESTADO", EstadoUsuarioEnum.NUEVO.getCodigo()); params.put("DIRECCION_USUARIO", comprobante.getCliente().getDireccion()); params.put("PK_CODIGO_COMP", comprobante.getCodigocomprobante()); params.put("CODIGO_DOCUMENTO", comprobante.getCoddoc()); params.put("ESTADO", EstadoComprobanteEnum.AUTORIZADO.getDescripcion()); params.put("CLAVE_ACCESO", comprobante.getClaveacceso()); params.put("SECUENCIAL", comprobante.getSecuencial()); params.put("FECHA_EMISION", utilitario.getFormatoFecha(comprobante.getFechaemision())); params.put("NUM_AUTORIZACION", comprobante.getNumAutorizacion()); params.put("FECHA_AUTORIZACION", utilitario.getFormatoFecha(comprobante.getFechaautoriza())); params.put("ESTABLECIM", comprobante.getEstab()); params.put("PTO_EMISION", comprobante.getPtoemi()); params.put("TOTAL", comprobante.getImportetotal()); params.put("CODIGO_EMPR", ParametrosSistemaEnum.CODIGO_EMPR.getCodigo()); params.put("CORREO_DOCUMENTO", comprobante.getCorreo()); //Para guardar el correo que se envio el comprobante byte[] bxml = archivoService.getXml(comprobante); StringBuilder postData = new StringBuilder(); postData.append("{"); for (Map.Entry<String, Object> param : params.entrySet()) { if (postData.length() != 1) { postData.append(','); }/* ww w . j a va 2s. c om*/ postData.append("\"").append(param.getKey()).append("\""); postData.append(":\""); postData.append(String.valueOf(param.getValue())).append("\""); } String encodedfileXML = new String(Base64.encodeBase64(bxml)); params.put("ARCHIVO_XML", encodedfileXML); //guarda en la nuebe el comprobante AUTORIZADO String filefield = "pdf"; String fileMimeType = "application/pdf"; 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; String fileName = comprobante.getClaveacceso() + ".pdf"; try { byte[] bpdf = archivoService.getPdf(comprobante); File file = File.createTempFile(comprobante.getClaveacceso(), ".tmp"); file.deleteOnExit(); try (FileOutputStream outputStream1 = new FileOutputStream(file);) { outputStream1.write(bpdf); //write the bytes and your done. outputStream1.close(); } catch (Exception e) { e.printStackTrace(); } FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(ParametrosSistemaEnum.CPANEL_WEB_COMPROBANTE.getCodigo()); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); 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: " + fileMimeType + 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); // Upload POST Data Iterator<String> keys = params.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); String value = String.valueOf(params.get(key)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(value); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); if (200 != connection.getResponseCode()) { throw new Exception("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage()); } inputStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader((inputStream))); String output; while ((output = br.readLine()) != null) { result += output; } System.out.println(result); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); //CAMBIA DE ESTADO A GUARDDADO EN LA NUBE comprobante.setEnNube(true); comprobanteDAO.actualizar(comprobante); } catch (Exception e) { guardo = false; throw new GenericException(e); } if (guardo) { //Guarda el detalle de la factura if (comprobante.getCoddoc().equals(TipoComprobanteEnum.FACTURA.getCodigo())) { for (DetalleComprobante detActual : comprobante.getDetalle()) { guardarDetalleComprobanteNube(detActual); } } } return guardo; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading page * resources as appropriate.// w w w . ja va 2 s .c om * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); log.debug("Start : sample " + urlStr); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { res.sampleEnd(); res.setResponseNoContent(); res.setSuccessful(true); return res; } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry; // Start with 0 so tries at least once, and retries at most // MAX_CONN_RETRIES times for (retry = 0; retry <= MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try // disconnection again conn.disconnect(); } setUseKeepAlive(false); continue; // try again } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); @SuppressWarnings("null") // Cannot be null here int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be // returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with // different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ // $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers // (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection // again // We don't want to continue using this connection, even if // KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection // again disconnect(conn); // Disconnect unless using KeepAlive } }
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;/* ww w . j a v a 2 s. c o 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; }