List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:edu.pdx.cecs.orcycle.NoteUploader.java
boolean uploadOneNote(long noteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from w w w . ja v a 2s . c o m*/ JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId); URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonNote; if (null != (jsonNote = getNoteJSON(noteId))) { try { String deviceId = userId; dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n"); dos.writeBytes( notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n"); if (null != imageData) { dos.writeBytes(notesep + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n"); dos.write(imageData); dos.writeBytes("\r\n"); } dos.writeBytes(notesep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } else { result = false; } } catch (IllegalStateException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (IOException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (JSONException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { NoteUploader.setPending(noteId, false); } return result; }
From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java
/****************************************************************************************** * Uploads the note to the server//from www .j a v a2s . c om ****************************************************************************************** * @param currentNoteId Unique note ID to be uploaded * @return True if uploaded, false if not ******************************************************************************************/ boolean uploadOneNote(long currentNoteId) { boolean result = false; final String postUrl = "http://FountainCityCycling.org/post/"; try { URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); /* Change protocol to 2 for Note, and change the point where you zip up the body. (Dont zip up trip body) Since notes don't work either, this may not solve it. */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject note = getNoteJSON(currentNoteId); deviceId = getDeviceId(); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"note\"\r\n\r\n" + note.toString() + "\r\n"); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"version\"\r\n\r\n" + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"device\"\r\n\r\n" + deviceId + "\r\n"); if (imageDataNull == false) { dos.writeBytes("--cycle*******notedata*******columbus\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n"); dos.write(imageData); dos.writeBytes("\r\n"); } dos.writeBytes("--cycle*******notedata*******columbus--\r\n"); dos.flush(); dos.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("KENNY", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); responseMessage = serverResponseMessage; responseCode = serverResponseCode; // 200 - 202 means successfully went to server and uploaded if (serverResponseCode == 200 || serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(currentNoteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } catch (IllegalStateException e) { Log.d("KENNY", "Note Catch: Illegal State Exception: " + e); e.printStackTrace(); return false; } catch (IOException e) { Log.d("KENNY", "Note Catch: IOException: " + e); e.printStackTrace(); return false; } catch (JSONException e) { Log.d("KENNY", "Note Catch: JSONException: " + e); e.printStackTrace(); return false; } return result; }
From source file:de.mpg.mpdl.inge.dataacquisition.DataHandlerBean.java
/** * Fetches a eSciDoc Record from eSciDoc system. * /*from w w w .j a v a 2 s . c o m*/ * @param identifier of the item * @return itemXML as String * @throws IdentifierNotRecognisedException * @throws RuntimeException */ private byte[] fetchEjbFile(FullTextVO ft, String identifier) throws IdentifierNotRecognisedException, RuntimeException { String itemXML = ""; String coreservice = ""; URLConnection contentUrl = null; de.mpg.mpdl.inge.xmltransforming.XmlTransforming xmlTransforming = new de.mpg.mpdl.inge.xmltransforming.xmltransforming.XmlTransformingBean(); byte[] input = null; try { if (this.currentSource.getName().equalsIgnoreCase("escidoc")) { itemXML = ServiceLocator.getItemHandler().retrieve(identifier); coreservice = PropertyReader.getFrameworkUrl(); } if (this.currentSource.getName().equalsIgnoreCase("escidocdev") || this.currentSource.getName().equalsIgnoreCase("escidocqa") || this.currentSource.getName().equalsIgnoreCase("escidocprod")) { itemXML = ServiceLocator.getItemHandler(ft.getFtUrl().toString()).retrieve(identifier); coreservice = ft.getFtUrl().toString(); } PubItemVO itemVO = xmlTransforming.transformToPubItem(itemXML); contentUrl = ProxyHelper.openConnection(new URL(coreservice + itemVO.getFiles().get(0).getContent())); HttpURLConnection httpConn = (HttpURLConnection) contentUrl; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file."); throw new FormatNotAvailableException(ft.getFtLabel()); case 302: String alternativeLocation = contentUrl.getHeaderField("Location"); ft.setFtUrl(new URL(alternativeLocation)); return fetchEjbFile(ft, identifier); case 200: this.logger.info("Source responded with 200."); GetMethod method = new GetMethod(coreservice + itemVO.getFiles().get(0).getContent()); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); break; case 403: throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } } catch (ItemNotFoundException e) { this.logger.error("Item with identifier " + identifier + " was not found.", e); throw new IdentifierNotRecognisedException(e); } catch (Exception e) { this.logger.error("An error occurred while retrieving the item " + identifier + ".", e); throw new RuntimeException(e); } return input; }
From source file:com.techventus.server.voice.Voice.java
/** * Use this login method to login - use captchaAnswer to answer a captcha challenge * @param pCaptchaAnswer (optional) String entered by the user as an answer to a CAPTCHA challenge. - null to make a normal login attempt * @param pCaptchaToken (optional) token which matches the response/url from the captcha challenge * @throws IOException if login encounters a connection error *//* w ww .jav a 2s .c om*/ public void login(String pCaptchaAnswer, String pCaptchaToken) throws IOException { String data = URLEncoder.encode("accountType", enc) + "=" + URLEncoder.encode(account_type, enc); data += "&" + URLEncoder.encode("Email", enc) + "=" + URLEncoder.encode(user, enc); data += "&" + URLEncoder.encode("Passwd", enc) + "=" + URLEncoder.encode(pass, enc); data += "&" + URLEncoder.encode("service", enc) + "=" + URLEncoder.encode(SERVICE, enc); data += "&" + URLEncoder.encode("source", enc) + "=" + URLEncoder.encode(source, enc); if (pCaptchaAnswer != null && pCaptchaToken != null) { data += "&" + URLEncoder.encode("logintoken", enc) + "=" + URLEncoder.encode(pCaptchaToken, enc); data += "&" + URLEncoder.encode("logincaptcha", enc) + "=" + URLEncoder.encode(pCaptchaAnswer, enc); } // Send data URL url = new URL(loginURLString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-agent", USER_AGENT); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response conn.connect(); int responseCode = conn.getResponseCode(); if (PRINT_TO_CONSOLE) System.out.println(loginURLString + " - " + conn.getResponseMessage()); InputStream is; if (responseCode == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); String line; String completelineDebug = ""; /* * A failure response contains an error code and a URL to an error page that can be displayed to the user. * If the error code is a CAPTCHA challenge, the response also includes a URL to a CAPTCHA image and a special * token. Your application should be able to solicit an answer from the user and then retry the login request. * To display the CAPTCHA image to the user, prefix the CaptchaUrl value with "http://www.google.com/accounts/", * for example: " http://www.google.com/accounts/Captcha?ctoken=HiteT4b0Bk5Xg18_AcVoP6-yFkHPibe7O9EqxeiI7lUSN". */ String lErrorString = "Unknown Connection Error."; // ex: Error=CaptchaRequired // String AuthToken = null; while ((line = rd.readLine()) != null) { completelineDebug += line + "\n"; if (line.contains("Auth=")) { this.authToken = line.split("=", 2)[1].trim(); if (PRINT_TO_CONSOLE) { System.out.println("Logged in to Google - Auth token received"); } } else if (line.contains("Error=")) { lErrorString = line.split("=", 2)[1].trim(); //error = getErrorEnumByCode(lErrorString); error = ERROR_CODE.valueOf(lErrorString); if (PRINT_TO_CONSOLE) System.out.println("Login error - " + lErrorString); } if (line.contains("CaptchaToken=")) { captchaToken = line.split("=", 2)[1].trim(); } if (line.contains("CaptchaUrl=")) { captchaUrl = "http://www.google.com/accounts/" + line.split("=", 2)[1].trim(); } if (line.contains("Url=")) { captchaUrl2 = line.split("=", 2)[1].trim(); } } wr.close(); rd.close(); // if (PRINT_TO_CONSOLE){ // System.out.println(completelineDebug); // } if (this.authToken == null) { AuthenticationException.throwProperException(error, captchaToken, captchaUrl); } String response = this.getRawPhonesInfo(); int phoneIndex = response.indexOf("gc-user-number-value\">"); this.phoneNumber = response.substring(phoneIndex + 22, phoneIndex + 36); this.phoneNumber = this.phoneNumber.replaceAll("[^a-zA-Z0-9]", ""); if (this.phoneNumber.indexOf("+") == -1) { this.phoneNumber = "+1" + this.phoneNumber; } }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;//from www. jav a2 s.co m if ((s = connect()) != Status.OK) { return s; } TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); String id = tcx.export(mID, writer); conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection(); conn.setInstanceFollowRedirects(false); addCookies(conn); getFormValues(conn); // execute the GET conn.disconnect(); String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE"); String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION"); String fileKey = SyncHelper.findName(formValues.keySet(), "FileUpload"); String uploadKey = SyncHelper.findName(formValues.keySet(), "UploadButton"); Part<StringWritable> part1 = new Part<StringWritable>(viewKey, new StringWritable(formValues.get(viewKey))); Part<StringWritable> part2 = new Part<StringWritable>(eventKey, new StringWritable(formValues.get(eventKey))); Part<StringWritable> part3 = new Part<StringWritable>(fileKey, new StringWritable(writer.toString())); part3.setContentType("application/octet-stream"); part3.setFilename("jonas.tcx"); Part<StringWritable> part4 = new Part<StringWritable>(uploadKey, new StringWritable(formValues.get(uploadKey))); Part<?> parts[] = { part1, part2, part3, part4 }; conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); addCookies(conn); SyncHelper.postMulti(conn, parts); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); String redirect = null; if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != HttpStatus.SC_OK) { Log.e(getName(), "FunBeatSynchronizer::upload() - got " + responseCode + ", msg: " + amsg); } getFormValues(conn); conn.disconnect(); viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE"); eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION"); String nextKey = SyncHelper.findName(formValues.keySet(), "NextButton"); String hidden = SyncHelper.findName(formValues.keySet(), "ChoicesHiddenField"); FormValues kv = new FormValues(); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(nextKey, "Nasta >>"); kv.put(hidden, "[ \"import///" + id + "///tcx\" ]"); String surl = BASE_URL + redirect; conn = (HttpURLConnection) new URL(surl).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } String html = getFormValues(conn); boolean ok = html.indexOf("r klar") > 0; Log.e(getName(), "ok: " + ok); conn.disconnect(); if (ok) { s = Status.OK; s.activityId = mID; } else { s = Status.CANCEL; } return s; } } catch (IOException e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * Fetches a eSciDoc Record from eSciDoc system. * //from w w w . j av a 2s. co m * @param identifier * of the item * @return itemXML as String * @throws IdentifierNotRecognisedException * @throws RuntimeException */ private byte[] fetchEjbFile(FullTextVO ft, String identifier) throws IdentifierNotRecognisedException, RuntimeException { String itemXML = ""; String coreservice = ""; URLConnection contentUrl = null; XmlTransforming xmlTransforming = new XmlTransformingBean(); byte[] input = null; try { if (this.currentSource.getName().equalsIgnoreCase("escidoc")) { itemXML = ServiceLocator.getItemHandler().retrieve(identifier); coreservice = ServiceLocator.getFrameworkUrl(); } if (this.currentSource.getName().equalsIgnoreCase("escidocdev") || this.currentSource.getName().equalsIgnoreCase("escidocqa") || this.currentSource.getName().equalsIgnoreCase("escidocprod")) { itemXML = ServiceLocator.getItemHandler(ft.getFtUrl().toString()).retrieve(identifier); coreservice = ft.getFtUrl().toString(); } PubItemVO itemVO = xmlTransforming.transformToPubItem(itemXML); contentUrl = ProxyHelper.openConnection(new URL(coreservice + itemVO.getFiles().get(0).getContent())); HttpURLConnection httpConn = (HttpURLConnection) contentUrl; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file."); throw new FormatNotAvailableException(ft.getFtLabel()); case 302: String alternativeLocation = contentUrl.getHeaderField("Location"); ft.setFtUrl(new URL(alternativeLocation)); return fetchEjbFile(ft, identifier); case 200: this.logger.info("Source responded with 200."); GetMethod method = new GetMethod(coreservice + itemVO.getFiles().get(0).getContent()); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); break; case 403: throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } } catch (ItemNotFoundException e) { this.logger.error("Item with identifier " + identifier + " was not found.", e); throw new IdentifierNotRecognisedException(e); } catch (Exception e) { this.logger.error("An error occurred while retrieving the item " + identifier + ".", e); throw new RuntimeException(e); } return input; }
From source file:net.myrrix.client.ClientRecommender.java
@Override public void ingest(Reader reader) throws TasteException { Map<Integer, Pair<Writer, HttpURLConnection>> writersAndConnections = Maps .newHashMapWithExpectedSize(partitions.size()); BufferedReader buffered = IOUtils.buffer(reader); try {/* w w w .j av a2s . c o m*/ try { String line; while ((line = buffered.readLine()) != null) { if (line.isEmpty() || line.charAt(0) == '#') { continue; } long userID; try { userID = Long.parseLong(COMMA.split(line).iterator().next()); } catch (NoSuchElementException nsee) { throw new TasteException(nsee); } catch (NumberFormatException nfe) { throw new TasteException(nfe); } int partition = LangUtils.mod(userID, partitions.size()); Pair<Writer, HttpURLConnection> writerAndConnection = writersAndConnections.get(partition); if (writerAndConnection == null) { HttpURLConnection connection = buildConnectionToAReplica(partition); Writer writer = IOUtils.buildGZIPWriter(connection.getOutputStream()); writerAndConnection = new Pair<Writer, HttpURLConnection>(writer, connection); writersAndConnections.put(partition, writerAndConnection); } Writer writer = writerAndConnection.getFirst(); writer.write(line); writer.write('\n'); } for (Pair<Writer, HttpURLConnection> writerAndConnection : writersAndConnections.values()) { // Want to know of output stream close failed -- maybe failed to write writerAndConnection.getFirst().close(); HttpURLConnection connection = writerAndConnection.getSecond(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new TasteException( connection.getResponseCode() + " " + connection.getResponseMessage()); } } } finally { for (Pair<Writer, HttpURLConnection> writerAndConnection : writersAndConnections.values()) { writerAndConnection.getFirst().close(); writerAndConnection.getSecond().disconnect(); } } } catch (IOException ioe) { throw new TasteException(ioe); } }
From source file:com.techventus.server.voice.Voice.java
/** * HTTP GET request for a given URL String. * /*from w ww. j a v a 2 s . c om*/ * @param urlString * the url string * @return the string * @throws IOException * Signals that an I/O exception has occurred. */ String get(String urlString) throws IOException { URL url = new URL(urlString); //+ "?auth=" + URLEncoder.encode(authToken, enc)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); conn.setRequestProperty("User-agent", USER_AGENT); conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true // Get the response conn.connect(); int responseCode = conn.getResponseCode(); if (PRINT_TO_CONSOLE) System.out.println(urlString + " - " + conn.getResponseMessage()); InputStream is; if (responseCode == 200) { is = conn.getInputStream(); } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) { redirectCounter++; if (redirectCounter > MAX_REDIRECTS) { redirectCounter = 0; throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : Too manny redirects. exiting."); } String location = conn.getHeaderField("Location"); if (location != null && !location.equals("")) { System.out.println(urlString + " - " + responseCode + " - new URL: " + location); return get(location); } else { throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : Received moved answer but no Location. exiting."); } } else { is = conn.getErrorStream(); } redirectCounter = 0; if (is == null) { throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : InputStream was null : exiting."); } String result = ""; try { // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\n\r"); } rd.close(); result = sb.toString(); } catch (Exception e) { throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - " + e.getLocalizedMessage()); } return result; }
From source file:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {// www .j a va 2 s . c om URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:com.techventus.server.voice.Voice.java
/** * Posts a settings change./*from ww w. ja v a2 s .c o m*/ * * @param requestURL the request url * @param paraString the para string * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private String postSettings(URL requestURL, String paraString) throws IOException { String out = ""; HttpURLConnection conn = (HttpURLConnection) requestURL.openConnection(); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); conn.setRequestProperty("User-agent", USER_AGENT); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream()); callwr.write(paraString); callwr.flush(); // Get the response conn.connect(); int responseCode = conn.getResponseCode(); if (PRINT_TO_CONSOLE) System.out.println(requestURL + " - " + conn.getResponseMessage()); InputStream is; if (responseCode == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader callrd = new BufferedReader(isr); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } if (PRINT_TO_CONSOLE) System.out.println(out); return out; }