List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.wareninja.opensource.common.wsrequest.WebServiceNew.java
public String webPost(String methodName, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os;//from ww w. j a v a 2 s .c o m ret = null; String postUrl = webServiceUrl + methodName; if (LOGGING.DEBUG) { Log.d(TAG, "POST URL: " + postUrl); } HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " WareNinjaAndroidSDK"); HttpParams httpParams = httpClient.getParams(); HttpProtocolParams.setUseExpectContinue(httpParams, false); Bundle dataparams = new Bundle(); for (String key : params.keySet()) { byte[] byteArr = null; try { byteArr = (byte[]) params.get(key); } catch (Exception ex1) { } if (byteArr != null) dataparams.putByteArray(key, byteArr); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); appendRequestHeaders(conn, headers); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((WareNinjaUtils.encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); String response = ""; try { response = WareNinjaUtils.read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = WareNinjaUtils.read(conn.getErrorStream()); } if (LOGGING.DEBUG) Log.d(TAG, "POST response: " + response); return response; }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) { HttpURLConnection urlConnection = null; URL myurl = null;//from w ww .j a v a 2 s . c om OutputStreamWriter wr = null; int responseCode = 0; String id = null; int error = 0; try { myurl = new URL(url_str + command); urlConnection = (HttpURLConnection) myurl.openConnection(); urlConnection.setRequestMethod(msgtype); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(coppereggApiTimeoutInMillis); urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76"); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); wr.write(payload); wr.flush(); responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn( "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype); error = 1; } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e); error = 1; } finally { if (urlConnection != null) { try { if (error > 0) { InputStream err = urlConnection.getErrorStream(); String errString = convertStreamToString(err); logger.warn("Reported error : " + errString); IoUtils2.closeQuietly(err); } else { InputStream in = urlConnection.getInputStream(); String theString = convertStreamToString(in); id = jparse(theString, ExpectInt); IoUtils2.closeQuietly(in); } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command : flushing http connection " + e); } } if (wr != null) { try { wr.close(); } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: closing OutputWriter " + e); } } } return (id); }
From source file:cn.org.eshow.framwork.http.AbHttpClient.java
/** * ?,???String,?????/*from w ww . j a va2s . c o m*/ * @param url * @param params * @return */ public void doRequest(final String url, final AbRequestParams params, final AbStringHttpResponseListener responseListener) { responseListener.setHandler(new ResponderHandler(responseListener)); mExecutorService.execute(new Runnable() { public void run() { HttpURLConnection urlConn = null; try { responseListener.sendStartMessage(); if (!AbAppUtil.isNetworkAvailable(mContext)) { Thread.sleep(200); responseListener.sendFailureMessage(AbHttpStatus.CONNECT_FAILURE_CODE, AbAppConfig.CONNECT_EXCEPTION, new AbAppException(AbAppConfig.CONNECT_EXCEPTION)); return; } String resultString = null; URL requestUrl = new URL(url); urlConn = (HttpURLConnection) requestUrl.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(mTimeout); urlConn.setReadTimeout(mTimeout); urlConn.setDoOutput(true); if (params != null) { urlConn.setRequestProperty("connection", "keep-alive"); urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + params.boundaryString()); MultipartEntity reqEntity = params.getMultiPart(); reqEntity.writeTo(urlConn.getOutputStream()); } else { urlConn.connect(); } if (urlConn.getResponseCode() == HttpStatus.SC_OK) { resultString = readString(urlConn.getInputStream()); } else { resultString = readString(urlConn.getErrorStream()); } resultString = URLEncoder.encode(resultString, encode); urlConn.getInputStream().close(); responseListener.sendSuccessMessage(AbHttpStatus.SUCCESS_CODE, resultString); } catch (Exception e) { e.printStackTrace(); AbLogUtil.i(mContext, "[HTTP POST]:" + url + ",error" + e.getMessage()); //??? responseListener.sendFailureMessage(AbHttpStatus.UNTREATED_CODE, e.getMessage(), new AbAppException(e)); } finally { if (urlConn != null) urlConn.disconnect(); responseListener.sendFinishMessage(); } } }); }
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 *//*from w w w. j a v a 2 s . 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.jmxtrans.embedded.output.CopperEggWriter.java
public void one_set(String mg_name, List<QueryResult> counters) { HttpURLConnection urlCxn = null; URL newurl = null;/*from w w w .j a v a2s . co m*/ try { newurl = new URL(url_str + "/samples/" + mg_name + ".json"); if (proxy == null) { urlCxn = (HttpURLConnection) newurl.openConnection(); } else { urlCxn = (HttpURLConnection) newurl.openConnection(proxy); } if (urlCxn != null) { urlCxn.setRequestMethod("POST"); urlCxn.setDoInput(true); urlCxn.setDoOutput(true); urlCxn.setReadTimeout(coppereggApiTimeoutInMillis); urlCxn.setRequestProperty("content-type", "application/json; charset=utf-8"); urlCxn.setRequestProperty("Authorization", "Basic " + basicAuthentication); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception: one_set: failed to connect to CopperEgg Service '{}' with proxy {}", newurl, proxy, e); return; } if (urlCxn != null) { try { cue_serialize(counters, urlCxn.getOutputStream()); int responseCode = urlCxn.getResponseCode(); if (responseCode != 200) { logger.warn("one_set: Failure {}: {} to send result to CopperEgg service {}", responseCode, urlCxn.getResponseMessage(), newurl); } try { InputStream in = urlCxn.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlCxn.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Execption one_set: Write-Exception flushing http connection", e); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Execption: one_set: Failure to send result to CopperEgg Service '{}' with proxy {}", newurl, proxy, e); } } }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {/* w w w .j a v a 2s . c o m*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }
From source file:com.techventus.server.voice.Voice.java
/** * Posts a settings change./*from w w w.ja v a 2 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; }
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 {/*from ww w . j av a 2 s. c o m*/ 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; }