List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:io.fabric8.devops.connector.DevOpsConnector.java
protected void triggerJenkinsWebHook(String jobUrl, String triggerUrl, String secret) { // lets check if this build is already running in which case do nothing String lastBuild = URLUtils.pathJoin(jobUrl, "/lastBuild/api/json"); JsonNode lastBuildJson = parseLastBuildJson(lastBuild); JsonNode building = null;/*from www . ja va 2 s .c o m*/ if (lastBuildJson != null && lastBuildJson.isObject()) { building = lastBuildJson.get("building"); if (building != null && building.isBoolean()) { if (building.booleanValue()) { getLog().info("Build is already running so lets not trigger another one!"); return; } } } getLog().info("Got last build JSON: " + lastBuildJson + " building: " + building); getLog().info("Triggering Jenkins webhook: " + triggerUrl); String json = "{}"; HttpURLConnection connection = null; try { URL url = new URL(triggerUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(json); out.close(); int status = connection.getResponseCode(); String message = connection.getResponseMessage(); getLog().info("Got response code from Jenkins: " + status + " message: " + message); if (status != 200) { getLog().error( "Failed to trigger job " + triggerUrl + ". Status: " + status + " message: " + message); } } catch (Exception e) { getLog().error("Failed to trigger jenkins on " + triggerUrl + ". " + e, e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:edu.cmu.cs.quiltview.RequestPullingService.java
private void pullRequest() { String resultTxt = " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis()); Log.i(LOG_TAG, "Begin pull." + resultTxt); getLocation();// www.j a va2 s.co m double latitude, longitude; if (mLocation != null) { Log.i(LOG_TAG, "Real Location"); latitude = mLocation.getLatitude(); longitude = mLocation.getLongitude(); } else { //TODO test real location /* * As we usually develop and demo indoor, the GPS location is not always * available. For the convenience of development, we use theses fixed fake * location. This is somewhere on Carnegie Mellon University campus * Wenlu Hu, April 2014 */ Log.i(LOG_TAG, "Fake Location"); latitude = 40.443469; //40.44416720; longitude = -79.943862; //-79.94336060; } Log.i(LOG_TAG, "Location: " + latitude + ", " + longitude); HttpURLConnection urlConnection = null; try { URL url = new URL(Const.quiltview_server_addr + "/latest/" + "?user_id=" + mSerialNumber + "&lat=" + latitude + "&lng=" + longitude); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Content-Type", "application/json"); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = urlConnection.getInputStream(); int responseLen = urlConnection.getContentLength(); Log.i(LOG_TAG, "Response Len = " + responseLen); //Read the json file byte[] jsonBuffer = new byte[responseLen]; Log.i(LOG_TAG, "Response Len = " + is.read(jsonBuffer)); String jsonString = new String(jsonBuffer, "UTF-8"); Log.i(LOG_TAG, "Got response: " + jsonString); try { JSONObject obj = (JSONObject) JSONValue.parse(jsonString); String query = obj.get("content").toString(); int queryID = Integer.parseInt(obj.get("query_id").toString()); int userID = Integer.parseInt(obj.get("user_id").toString()); String imagePath = obj.get("image").toString(); Log.i(LOG_TAG, userID + ", " + queryID + ": " + query + "&" + imagePath); imagePath = saveImageToLocal(imagePath); recordForQuery(query, queryID, userID, imagePath); } catch (NullPointerException ex) { Log.i(LOG_TAG, "No valid query"); } } else { Log.e(LOG_TAG, "Response " + urlConnection.getResponseCode() + ":" + urlConnection.getResponseMessage()); } } catch (MalformedURLException ex) { Log.e(LOG_TAG, "", ex); } catch (IOException ex) { Log.e(LOG_TAG, "", ex); } finally { if (urlConnection != null) urlConnection.disconnect(); } }
From source file:net.myrrix.client.ClientRecommender.java
private FastIDSet getCluster(int n, boolean user) throws TasteException { String urlPath = '/' + (user ? "user" : "item") + "/clusters/" + n; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(0L)) { HttpURLConnection connection = null; try {//w ww . j a v a 2 s.co m connection = buildConnectionToReplica(replica, urlPath, "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: FastIDSet members = new FastIDSet(); consumeIDs(connection, members); return members; case HttpURLConnection.HTTP_NOT_IMPLEMENTED: throw new UnsupportedOperationException(); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:io.fabric8.devops.connector.DevOpsConnector.java
protected void postJenkinsBuild(String jobName, String xml, boolean create) { String address = getServiceUrl(ServiceNames.JENKINS, false, namespace, jenkinsNamespace); if (Strings.isNotBlank(address)) { String jobUrl = URLUtils.pathJoin(address, "/job", jobName, "config.xml"); if (create && !existsXmlURL(jobUrl)) { jobUrl = URLUtils.pathJoin(address, "/createItem") + "?name=" + jobName; }/* ww w.j a va 2s.c om*/ getLog().info("POSTING the jenkins job to: " + jobUrl); getLog().debug("Jenkins XML: " + xml); HttpURLConnection connection = null; try { URL url = new URL(jobUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(xml); out.close(); int status = connection.getResponseCode(); String message = connection.getResponseMessage(); getLog().info("Got response code from Jenkins: " + status + " message: " + message); if (status != 200) { getLog().error("Failed to register job " + jobName + " on " + jobUrl + ". Status: " + status + " message: " + message); } } catch (Exception e) { getLog().error("Failed to register jenkins on " + jobUrl + ". " + e, e); } finally { if (connection != null) { connection.disconnect(); } } } }
From source file:fr.gael.dhus.olingo.ODataClient.java
/** * Performs the execution of an OData command through HTTP. * /*w ww . ja v a2 s. co m*/ * @param absolute_uri The not that relative URI to query. * @param content_type The content type can be JSON, XML, Atom+XML, * see {@link OdataContentType}. * @param http_method {@code "POST", "GET", "PUT", "DELETE", ...} * * @return The response as a stream. You may assume it's UTF-8 encoded. * * @throws HttpException if the server emits an HTTP error code. * @throws IOException if an error occurred connecting to the server. */ private InputStream execute(String absolute_uri, ContentType content_type, String http_method) throws IOException { URL url = new URL(absolute_uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // HTTP Basic Authentication. String userpass = this.username + ":" + this.password; String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); // GET, POST, ... connection.setRequestMethod(http_method); // `Accept` for GET, `Content-Type` for POST and PUT. connection.setRequestProperty("Accept", content_type.type()); connection.connect(); int resp_code = connection.getResponseCode(); // 2XX == success, 3XX == redirect (handled by the HTTPUrlConnection) if (resp_code == 200) { InputStream content = connection.getInputStream(); content = logRawContent(http_method + " request on uri '" + absolute_uri + "' with content:\n", content, "\n"); return content; } else if (resp_code >= 300 && resp_code < 400) { // HttpURLConnection should follow redirections automatically, // but won't follow if the protocol changes. // See https://bugs.openjdk.java.net/browse/JDK-4620571 // If the scheme has changed (http -> https) follow the redirection. String redi_uri = connection.getHeaderField("Location"); if (redi_uri == null || redi_uri.isEmpty()) throw new HttpException(connection.getResponseCode(), connection.getResponseMessage() + " redirection failure."); if (!redi_uri.startsWith("https")) throw new HttpException(connection.getResponseCode(), connection.getResponseMessage() + " unsecure redirection."); LOGGER.debug("Attempting redirection to " + redi_uri); connection.disconnect(); return execute(redi_uri, content_type, http_method); } else { throw new HttpException(connection.getResponseCode(), connection.getResponseMessage()); } }
From source file:jetbrains.buildServer.vmgr.agent.Utils.java
public String executeVSIFLaunch(String[] vsifs, String url, boolean requireAuth, String user, String password, BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath) throws Exception { boolean notInTestMode = true; if (logger == null) { notInTestMode = false;/*w ww . jav a 2s. c om*/ } String apiURL = url + "/rest/sessions/launch"; for (int i = 0; i < vsifs.length; i++) { if (notInTestMode) { logger.message("vManager vAPI - Trying to launch vsif file: '" + vsifs[i] + "'"); } String input = "{\"vsif\":\"" + vsifs[i] + "\"}"; HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", dynamicUserId, buildID, workPlacePath, logger); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) { String reason = ""; if (conn.getResponseCode() == 503) reason = "vAPI process failed to connect to remote vManager server."; if (conn.getResponseCode() == 401) reason = "Authentication Error"; if (conn.getResponseCode() == 412) reason = "vAPI requires vManager 'Integration Server' license."; if (conn.getResponseCode() == 406) reason = "VSIF file '" + vsifs[i] + "' was not found on file system, or is not accessed by the vAPI process."; String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")"; if (notInTestMode) { logger.message(errorMessage); logger.message(conn.getResponseMessage()); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder result = new StringBuilder(); String output; while ((output = br.readLine()) != null) { result.append(output); } logger.message(result.toString()); } System.out.println(errorMessage); return errorMessage; } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder result = new StringBuilder(); String output; while ((output = br.readLine()) != null) { result.append(output); } conn.disconnect(); JSONObject tmp = JSONObject.fromObject(result.toString()); String textOut = "Session Launch Success: Session ID: " + tmp.getString("value"); if (notInTestMode) { logger.message(textOut); } else { System.out.println(textOut); } } return "success"; }
From source file:github.nisrulz.optimushttp.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;// w w w . j a va 2 s . c o m BufferedReader reader = null; String username = params[0].getUsername(); String password = params[0].getPassword(); String authStringEnc = null; if (username != null && password != null) { String authString = username + ":" + password; byte[] authEncBytes; authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT); authStringEnc = new String(authEncBytes); } String uri = params[0].getUri(); if (params[0].getMethod().equals("GET")) { uri += "?" + params[0].getEncodedParams(); } try { StringBuilder sb; // create the HttpURLConnection url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (authStringEnc != null) { connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT") || params[0].getMethod().equals("DELETE")) { // enable writing output to this url connection.setDoOutput(true); } if (params[0].getMethod().equals("POST")) { connection.setRequestMethod("POST"); } else if (params[0].getMethod().equals("GET")) { connection.setRequestMethod("GET"); } else if (params[0].getMethod().equals("PUT")) { connection.setRequestMethod("PUT"); } else if (params[0].getMethod().equals("DELETE")) { connection.setRequestMethod("DELETE"); } // give it x seconds to respond connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty("Content-Type", contentType); for (int i = 0; i < headerMap.size(); i++) { connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i)); } connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length); connection.connect(); if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(params[0].getEncodedParams()); writer.flush(); writer.close(); } // read the output from the server InputStream in; resCode = connection.getResponseCode(); resMsg = connection.getResponseMessage(); if (resCode != HttpURLConnection.HTTP_OK) { in = connection.getErrorStream(); } else { in = connection.getInputStream(); } reader = new BufferedReader(new InputStreamReader(in)); sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } sb.append(resCode).append(" : ").append(resMsg); return sb.toString(); } catch (Exception e) { listener.onFailure(Integer.toString(resCode) + " : " + resMsg); e.printStackTrace(); } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return null; }
From source file:edu.pdx.cecs.orcycle.UserInfoUploader.java
boolean uploadUserInfoV4() { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from www .j a v a 2 s . c om*/ JSONArray userResponses = getUserResponsesJSON(); 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 jsonUser; if (null != (jsonUser = getUserJSON())) { try { String deviceId = userId; dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n"); dos.writeBytes( fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n"); dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(fieldSep + ContentField("userResponses") + userResponses.toString() + "\r\n"); dos.writeBytes(fieldSep); 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) { // TODO: Record somehow that data was uploaded successfully result = true; } } else { result = false; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.odoko.solrcli.actions.CrawlPostAction.java
/** * Reads data from the data stream and posts it to solr, * writes to the response to output/*from w w w .j ava2s. co m*/ * @return true if success */ public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) { boolean success = true; if(type == null) type = DEFAULT_CONTENT_TYPE; HttpURLConnection urlc = null; try { try { urlc = (HttpURLConnection) url.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { fatal("Shouldn't happen: HttpURLConnection doesn't support POST??"+e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", type); if (null != length) urlc.setFixedLengthStreamingMode(length); } catch (IOException e) { fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); success = false; } OutputStream out = null; try { out = urlc.getOutputStream(); pipe(data, out); } catch (IOException e) { fatal("IOException while posting data: " + e); success = false; } finally { try { if(out!=null) out.close(); } catch (IOException x) { /*NOOP*/ } } InputStream in = null; try { if (HttpURLConnection.HTTP_OK != urlc.getResponseCode()) { warn("Solr returned an error #" + urlc.getResponseCode() + " " + urlc.getResponseMessage()); success = false; } in = urlc.getInputStream(); pipe(in, output); } catch (IOException e) { warn("IOException while reading response: " + e); success = false; } finally { try { if(in!=null) in.close(); } catch (IOException x) { /*NOOP*/ } } } finally { if(urlc!=null) urlc.disconnect(); } return success; }
From source file:de.mpg.mpdl.inge.dataacquisition.DataHandlerBean.java
/** * Retrieves the content of a component from different escidoc instances. * /*from w w w .j av a 2 s . c om*/ * @param identifier * @param url * @return content of a component as byte[] */ public byte[] retrieveComponentContent(String identifier, String url) { String coreservice = ""; URLConnection contentUrl; byte[] input = null; String sourceName = this.util.trimSourceName("escidoc", identifier); DataSourceVO source = this.sourceHandler.getSourceByName(sourceName); if (sourceName.equalsIgnoreCase("escidoc")) { try { coreservice = PropertyReader.getFrameworkUrl(); } catch (Exception e) { this.logger.error("Framework Access threw an exception.", e); return null; } } if (sourceName.equalsIgnoreCase("escidocdev") || sourceName.equalsIgnoreCase("escidocqa") || sourceName.equalsIgnoreCase("escidocprod") || sourceName.equalsIgnoreCase("escidoctest")) { // escidoc source has only one dummy ft record FullTextVO ft = source.getFtFormats().get(0); coreservice = ft.getFtUrl().toString(); } try { contentUrl = ProxyHelper.openConnection(new URL(coreservice + url)); HttpURLConnection httpConn = (HttpURLConnection) contentUrl; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Component content could not be fetched."); throw new RuntimeException("Component content could not be fetched. (503)"); case 200: this.logger.info("Source responded with 200."); GetMethod method = new GetMethod(coreservice + url); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); break; case 403: throw new AccessException("Access to component content is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } } catch (Exception e) { this.logger.error("An error occurred while retrieving the item " + identifier + ".", e); throw new RuntimeException(e); } return input; }