List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:com.zaizi.sensefy.service.impl.SensefyServiceImpl.java
/** * Send a query to Sensefy./* ww w . ja va 2s. com*/ * * @param method the http method to use * @param url the url to call * @return the answer from the Sensefy server in a json-formatted string * @throws IOException when failing to properly query the Sensefy server */ private String querySensefy(String method, URL url) throws IOException { if (!RequestMethod.GET.toString().equals(method)) { // We only support GET requests for now throw new NotImplementedException(); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(RequestMethod.GET.toString()); try (InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return sb.toString(); } else { LOGGER.error("Failed to query Sensefy with the request: " + method + " " + url.toString() + ". Sensefy returned with the code " + conn.getResponseCode() + " and the message " + conn.getResponseMessage()); return null; } } }
From source file:org.hawkular.apm.client.api.rest.AbstractRESTClient.java
public <T> T parseResultsIntoJson(HttpURLConnection connection, TypeReference<T> typeReference) { try {/*w w w. j a v a 2s . co m*/ String response = getResponse(connection); if (connection.getResponseCode() == 200) { if (log.isLoggable(Logger.Level.FINEST)) { log.finest("Returned json=[" + response + "]"); } if (!response.trim().isEmpty()) { try { return mapper.readValue(response, typeReference); } catch (Throwable t) { log.log(Logger.Level.SEVERE, "Failed to deserialize", t); } } } else { if (log.isLoggable(Logger.Level.FINEST)) { log.finest("Failed to get results: status=[" + connection.getResponseCode() + "]:" + connection.getResponseMessage()); } } } catch (Exception e) { log.log(Logger.Level.SEVERE, "Failed to get results", e); } return null; }
From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java
private String connect(String strURL) throws Exception { URL url = new URL(strURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); m_consumer.sign(request);//from w w w . ja v a 2s. co m request.connect(); if (request.getResponseCode() == 200) { String strResponse = ""; InputStreamReader in = new InputStreamReader((InputStream) request.getContent()); BufferedReader buff = new BufferedReader(in); for (String strLine = ""; strLine != null; strLine = buff.readLine()) { strResponse += strLine + "\n"; } in.close(); return strResponse; } else { throw new Exception( "Mendeley Server returned " + request.getResponseCode() + ": " + request.getResponseMessage()); } }
From source file:com.ab.network.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w w w. j ava 2s. 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); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. 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) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:org.runnerup.export.GarminSynchronizer.java
private void setWorkoutType(Sport s, String garminID) throws Exception { if (s == Sport.RUNNING || s == Sport.BIKING || s == Sport.OTHER) { //nothing to do return;/*from w w w. ja v a2 s . co m*/ } String value = sport2garminMap.get(s); //only change workout type if sport is supported by Garmin.. if (value == null) { Log.w(getName(), "Workout of type " + Sport.valueOf(s.getDbValue()) + " not supported by Garmin"); return; } HttpURLConnection conn = (HttpURLConnection) new URL(SET_TYPE_URL + garminID).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); addCookies(conn); FormValues fv = new FormValues(); fv.put("value", value); Log.e(getName(), "Setting sport activity to " + value + " for workout " + garminID); SyncHelper.postData(conn, fv); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK) { JSONObject reply = SyncHelper.parse(new BufferedReader(new InputStreamReader( // if "activityType" not in res or res["activityType"]["key"] != acttype: conn.getInputStream()))); conn.disconnect(); } else { throw new Exception("Impossible to connect" + responseCode + amsg); } }
From source file:com.bigstep.datalake.DLFileSystem.java
private static Map<?, ?> validateResponse(final HttpOpParam.Op op, final HttpURLConnection conn, boolean unwrapException) throws IOException { final int code = conn.getResponseCode(); // server is demanding an authentication we don't support if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { // match hdfs/rpc exception throw new AccessControlException(conn.getResponseMessage()); }//from ww w .j a v a2 s. c om if (code != op.getExpectedHttpResponseCode()) { final Map<?, ?> m; try { m = jsonParse(conn, true); } catch (Exception e) { throw new IOException( "Unexpected HTTP response: code=" + code + " != " + op.getExpectedHttpResponseCode() + ", " + op.toQueryString() + ", message=" + conn.getResponseMessage(), e); } if (m == null) { throw new IOException( "Unexpected HTTP response: code=" + code + " != " + op.getExpectedHttpResponseCode() + ", " + op.toQueryString() + ", message=" + conn.getResponseMessage()); } else if (m.get(RemoteException.class.getSimpleName()) == null) { return m; } IOException re = JsonUtil.toRemoteException(m); // extract UGI-related exceptions and unwrap InvalidToken // the NN mangles these exceptions but the DN does not and may need // to re-fetch a token if either report the token is expired if (re.getMessage() != null && re.getMessage().startsWith(SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER)) { String[] parts = re.getMessage().split(":\\s+", 3); re = new RemoteException(parts[1], parts[2]); re = ((RemoteException) re).unwrapRemoteException(SecretManager.InvalidToken.class); } throw unwrapException ? toIOException(re) : re; } return null; }
From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java
private HttpResponse performNormalREquest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w ww .j a v a 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); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. 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) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:neal.http.impl.httpstack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, HttpErrorCollection.AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w w w . jav a 2 s . co 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); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. 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) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.autonavi.gxdtaojin.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from ww w . jav a 2s .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 = null; try { parsedUrl = new URL(url); } catch (Throwable t) { t.printStackTrace(); parsedUrl = new URL("http://www.google.com"); } HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. 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) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.mome.main.netframe.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());// w w w . j a v a 2s . co 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); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. 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) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }