List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.dryver.Activities.ActivityRequestMap.java
/** * Opens a HTTPS request and sends the URL needed to get routes. * The data is saved to a string (Google direction returns a JSON object) * * @param directionURL//w w w.j av a 2s . c om * @return JSON object as a String * @throws IOException * @see URL * @see HttpURLConnection */ public String getDataFromUrl(String directionURL) throws IOException { URL url = new URL(directionURL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = urlConnection.getInputStream(); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(urlConnection.getResponseMessage() + ": with " + directionURL); } int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); return new String(out.toByteArray()); } finally { urlConnection.disconnect(); } }
From source file:org.apache.tez.runtime.library.shuffle.common.Fetcher.java
private void validateConnectionResponse(HttpURLConnection connection, URL url, String msgToEncode, String encHash) throws IOException { int rc = connection.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) { throw new IOException( "Got invalid response code " + rc + " from " + url + ": " + connection.getResponseMessage()); }//from w ww . j a va2 s . co m if (!ShuffleHeader.DEFAULT_HTTP_HEADER_NAME .equals(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME)) || !ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION .equals(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION))) { throw new IOException("Incompatible shuffle response version"); } // get the replyHash which is HMac of the encHash we sent to the server String replyHash = connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH); if (replyHash == null) { throw new IOException("security validation of TT Map output failed"); } if (LOG.isDebugEnabled()) { LOG.debug("url=" + msgToEncode + ";encHash=" + encHash + ";replyHash=" + replyHash); } // verify that replyHash is HMac of encHash SecureShuffleUtils.verifyReply(replyHash, encHash, shuffleSecret); LOG.info("for url=" + msgToEncode + " sent hash and receievd reply"); }
From source file:org.runnerup.export.GarminSynchronizer.java
private void expectResponse(HttpURLConnection conn, int code, String string) throws IOException { if (conn.getResponseCode() != code) { throw new IOException( string + ", code: " + conn.getResponseCode() + ", msg: " + conn.getResponseMessage()); }/*from w w w . j a va 2 s . c o m*/ }
From source file:io.mapzone.arena.refine.OrgPersonSplitTableRefineFunction.java
protected Point coordinateForOrganisation(final String organisation, final String plz, final String strasseHausNr) throws Exception { if (StringUtils.isBlank(plz) || StringUtils.isBlank(strasseHausNr)) { return null; }/*from ww w.j a va 2s.c o m*/ final String search1 = "\"lat\":"; final String search2 = ",\"lng\":"; final String search3 = "}"; final String key = "AAdiimU0EwFAoY3G7M7hFx694EdRTuSa"; final String location = URLEncoder.encode(Joiner.on(", ").join(plz, strasseHausNr), "UTF-8"); if (locations.containsKey(location)) { String coord = locations.getProperty(location); String[] coords = coord.split("\\|"); return GEOMETRYFACTORY .createPoint(new Coordinate(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]))); } else { final String url = String.format( "http://www.mapquestapi.com/geocoding/v1/address?key=%1$2s&location=%2$2s", key, location); final HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); con.addRequestProperty("Accept", "application/json"); con.setDoInput(true); con.setDoOutput(true); try { if (con.getResponseCode() != 200) { System.err.println("Keine Koordinate fr " + organisation + ": " + con.getResponseMessage()); } else { final String out = IOUtils.toString(con.getInputStream()); int index1 = out.indexOf(search1); if (index1 > 0) { String out2 = out.substring(index1 + search1.length()); int index3 = out2.indexOf(search3); if (index3 > 0) { out2 = out2.substring(0, index3); int index2 = out2.indexOf(search2); if (index2 > 0) { final String latitude = out2.substring(0, index2); final String longitude = out2.substring(index2 + search2.length()); Point point = (latitude != null && longitude != null) ? GEOMETRYFACTORY.createPoint( new Coordinate(Double.parseDouble(longitude), Double.parseDouble(latitude))) : null; return point; } } } } } finally { con.disconnect(); } } return null; }
From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java
public String downloadDatabase() { boolean flag = false; HttpURLConnection urlConnection = null; OutputStream myOutput = null; byte[] buffer = null; InputStream inputStream = null; String message = FAIL;/*from ww w . ja v a 2 s .c om*/ System.out.print(downloadDBURL); try { URL url = new URL(downloadDBURL); urlConnection = (HttpURLConnection) url.openConnection(); System.out.println("##Request Sent..."); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(20000); urlConnection.setReadTimeout(10000); urlConnection.connect(); int Http_Result = urlConnection.getResponseCode(); String res = urlConnection.getResponseMessage(); System.out.println(res); System.out.println(String.valueOf(Http_Result)); if (Http_Result == HttpURLConnection.HTTP_OK) { String contentType = urlConnection.getContentType(); inputStream = urlConnection.getInputStream(); System.out.println(contentType); if (contentType.equals("application/octet-stream")) { buffer = new byte[1024]; myOutput = new FileOutputStream(this.dbFile); int length; while ((length = inputStream.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); inputStream.close(); flag = true; message = SUCCESS; } else if (contentType.equals("application/json; charset=UTF-8")) { message = FAIL; flag = false; String responce = convertStreamToString(inputStream); System.out.println(responce); try { JSONObject jsResponce = new JSONObject(responce); message = jsResponce.getString("message"); } catch (JSONException e) { // addError(screenName, "Json error in downloadDatabase", e.getMessage()); System.out.println(e.toString()); } } } } catch (Exception ex) { System.out.println("##ROrder while downloading database" + ex.toString()); //addError(screenName, "downloadDatabase", ex.getMessage()); } return message; }
From source file:io.mindmaps.engine.loader.DistributedLoader.java
private String executePost(HttpURLConnection connection, String body) { try {// www . ja v a 2s.c om // create post connection.setRequestMethod(REST.HttpConn.POST_METHOD); connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE); // add body and execute connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8)); // get response return connection.getResponseMessage(); } catch (HTTPException e) { LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(), e.getStatusCode(), getResponseMessage(connection), body)); } catch (IOException e) { LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString())); } return null; }
From source file:org.myframe.http.HttpConnectStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from ww w . j a v a 2 s.c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { String value = ""; for (String v : header.getValue()) { value += (v + "; "); } Header h = new BasicHeader(header.getKey(), value); response.addHeader(h); } } return response; }
From source file:org.kymjs.kjframe.http.HttpConnectStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); //just marker by chenlin map.putAll(request.getHeaders());/*from w w w.j ava 2 s. c o m*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { String value = ""; for (String v : header.getValue()) { value += (v + "; "); } Header h = new BasicHeader(header.getKey(), value); response.addHeader(h); } } return response; }
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
protected String createErrorMessage(IOException ioe, HttpURLConnection connection) throws IOException { String errorMessage = IOUtils.toString(connection.getErrorStream()); if (!StringUtils.isEmpty(errorMessage)) { return errorMessage; }/*www . j a v a 2 s .com*/ StringBuilder builder = new StringBuilder("Connection to ").append(connection.getURL()); String reason = connection.getResponseMessage(); if (!StringUtils.isEmpty(reason)) { builder.append(": ").append(reason); } return builder.toString(); }