List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:de.ub0r.android.websms.connector.common.BasicConnector.java
/** * Parse HTTP response code. Default implementation throws * {@link WebSMSException} if response != HTTP_OK. * //from w ww .j av a 2 s .co m * @param context * {@link Context} * @param response * {@link HttpResponse} */ protected void parseResponseCode(final Context context, final HttpResponse response) { final int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { Log.e(TAG, "HTTP Status Line: " + response.getStatusLine().toString()); Log.e(TAG, "HTTP Headers:"); for (Header h : response.getAllHeaders()) { Log.e(TAG, h.getName() + ": " + h.getValue()); } try { final String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); Log.e(TAG, "HTTP Body:"); for (String l : htmlText.split("\n")) { Log.e(TAG, l); } } catch (Exception e) { Log.w(TAG, "error getting content", e); } throw new WebSMSException(context, R.string.error_http, String.valueOf(resp)); } }
From source file:com.entertailion.android.dial.HttpRequestHelper.java
public InputStream getHttpStream(String urlString) throws IOException { InputStream in = null;//from www . j a v a 2s .c om int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception e) { throw new IOException("Error connecting"); } // end try-catch return in; }
From source file:org.zywx.wbpalmstar.plugin.uexiconlist.utils.IconListUtils.java
private static byte[] downloadImageFromNetwork(String url) { InputStream is = null;/* w w w . j ava 2 s . com*/ byte[] data = null; try { HttpGet httpGet = new HttpGet(url); BasicHttpParams httpParams = new BasicHttpParams(); HttpResponse httpResponse = new DefaultHttpClient(httpParams).execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpURLConnection.HTTP_OK) { is = httpResponse.getEntity().getContent(); data = transStreamToBytes(is, 4096); } } catch (Exception e) { e.printStackTrace(); } return data; }
From source file:com.rothconsulting.android.websms.connector.yallo.ConnectorYallo.java
/** * Send data./*from w ww .j a v a 2s .co m*/ * * @param context * {@link Context} * @param packetData * packetData * @throws WebSMSException * WebSMSException */ private void sendData(final String url, final Context context, final ArrayList<BasicNameValuePair> postParameter, final boolean parseHtml) throws WebSMSException { this.log("Start sendData"); try { // get Connection this.log(url); HttpOptions httpOptions = new HttpOptions(); httpOptions.url = url; httpOptions.userAgent = USER_AGENT; httpOptions.trustAll = true; this.log("UrlEncodedFormEntity()"); if (postParameter != null) { httpOptions.postData = new UrlEncodedFormEntity(postParameter, YALLO_ENCODING); } this.log("send data: getHttpClient(...)"); HttpResponse response = Utils.getHttpClient(httpOptions); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); if (htmlText == null || htmlText.length() == 0) { throw new WebSMSException(context, R.string.error_service); } this.log("--HTTP RESPONSE--"); this.log(htmlText); this.log("--HTTP RESPONSE--"); if (parseHtml) { // Guthaben CHF int indexStartGuthaben = htmlText.indexOf("Ihr Guthaben:"); int textLenght = 14; if (indexStartGuthaben == -1) { indexStartGuthaben = htmlText.indexOf("Votre crdit:"); textLenght = 14; } if (indexStartGuthaben == -1) { indexStartGuthaben = htmlText.indexOf("Il suo credito:"); textLenght = 16; } if (indexStartGuthaben == -1) { indexStartGuthaben = htmlText.indexOf("O seu saldo:"); textLenght = 13; } if (indexStartGuthaben == -1) { indexStartGuthaben = htmlText.indexOf("Your credit:"); textLenght = 13; } this.GUTHABEN_CHF = htmlText.substring(indexStartGuthaben + textLenght, indexStartGuthaben + textLenght + 11); this.log("indexOf Guthaben=" + indexStartGuthaben + " -- Guthaben=" + this.GUTHABEN_CHF); // Gratis SMS int indexStartSMSGuthaben = htmlText.indexOf("SMS gratis,"); if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS gratuits,"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS gratuiti,"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS gratuitos,"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("free SMS,"); } this.GUTHABEN_SMS_GRATIS = htmlText.substring(indexStartSMSGuthaben - 3, indexStartSMSGuthaben - 1); this.log("indexOf SMS gratis=" + indexStartSMSGuthaben + " -- " + this.GUTHABEN_SMS_GRATIS); // Gekaufte SMS indexStartSMSGuthaben = htmlText.indexOf("SMS gekauft"); if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS achets"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS acquistati"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("SMS comprado"); } if (indexStartSMSGuthaben == -1) { indexStartSMSGuthaben = htmlText.indexOf("purchased SMS"); } this.GUTHABEN_SMS_BEZAHLT = htmlText.substring(indexStartSMSGuthaben - 3, indexStartSMSGuthaben - 1); this.log("indexOf SMS gekauft=" + indexStartSMSGuthaben + " -- SMS gekauft=" + this.GUTHABEN_SMS_BEZAHLT); this.setBalance(context); } htmlText = null; } catch (Exception e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
From source file:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java
private void getCredentialsForDevice(final RoutingContext ctx) { // mandatory params final String tenantId = getTenantParam(ctx); final String deviceId = getDeviceIdParam(ctx); logger.debug("getCredentialsForDevice [tenant: {}, device-id: {}]]", tenantId, deviceId); final JsonObject requestMsg = CredentialsConstants.getServiceGetRequestAsJson(tenantId, deviceId, null, CredentialsConstants.SPECIFIER_WILDCARD); sendAction(ctx, requestMsg,/* w ww .ja v a 2 s . co m*/ getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_OK, null)); }
From source file:com.aptana.jira.core.JiraManager.java
/** * Creates a JIRA ticket./*from w w w .j a v a 2 s . co m*/ * * @param type * the issue type (bug, feature, or improvement) * @param priority * the issue's priority * @param severity * the issue's severity (Blocker, Major, Minor, Trivial, None) * @param summary * the summary of the ticket * @param description * the description of the ticket * @return the JIRA issue created * @throws JiraException * @throws IOException */ public JiraIssue createIssue(JiraIssueType type, JiraIssueSeverity severity, String summary, String description) throws JiraException, IOException { if (user == null) { throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn); } HttpURLConnection connection = null; try { connection = createConnection(getCreateIssueURL(), user.getUsername(), user.getPassword()); connection.setRequestMethod("POST"); //$NON-NLS-1$ connection.setDoOutput(true); String severityJSON; String versionString; if ((TITANIUM_COMMUNITY.equals(projectKey) && type == JiraIssueType.IMPROVEMENT) || (!TITANIUM_COMMUNITY.equals(projectKey) && type != JiraIssueType.BUG)) { // Improvements in TC don't get Severities, nor do Story or Improvements in Aptana Studio! severityJSON = StringUtil.EMPTY; } else { severityJSON = severity.getParameterValue() + ",\n"; //$NON-NLS-1$ } // If we're submitting against TC, we can't do version, we need to stuff that into the Environment if (TITANIUM_COMMUNITY.equals(projectKey)) { versionString = MessageFormat.format("\"{0}\": \"{1}\"", PARAM_ENVIRONMENT, getProjectVersion()); //$NON-NLS-1$ } else { versionString = "\"" + PARAM_VERSION + "\": [{\"name\": \"" + getProjectVersion() + "\"}]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // @formatter:off String data = "{\n" + //$NON-NLS-1$ " \"fields\": {\n" + //$NON-NLS-1$ " \"project\":\n" + //$NON-NLS-1$ " { \n" + //$NON-NLS-1$ " \"key\": \"" + projectKey + "\"\n" + //$NON-NLS-1$ //$NON-NLS-2$ " },\n" + //$NON-NLS-1$ " \"summary\": \"" + summary.replaceAll("\"", "'") + "\",\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ " \"description\": \"" //$NON-NLS-1$ + description.replaceAll("\"", "'").replaceAll("\n", Matcher.quoteReplacement("\\n")) + "\",\n" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$ + " \"issuetype\": {\n" + " \"name\": \"" + type.getParameterValue(projectKey) + "\"\n" + //$NON-NLS-3$ " },\n" + //$NON-NLS-1$ severityJSON + " " + versionString + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ " }\n" + //$NON-NLS-1$ "}"; //$NON-NLS-1$ // @formatter:on OutputStream out = connection.getOutputStream(); IOUtil.write(out, data); out.close(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { String output = IOUtil.read(connection.getInputStream()); return createIssueFromJSON(output); } // failed to create the ticket // TODO Parse the response as JSON! throw new JiraException(IOUtil.read(connection.getErrorStream())); } catch (JiraException je) { throw je; } catch (Exception e) { throw new JiraException(e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java
@POST @Path("/repo") @Produces(MediaType.APPLICATION_JSON)//ww w .ja v a2 s .c o m @ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") }) public HttpResponse updateRepository( @ApiParam(value = "Data in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/gamifier/repo"); long randomLong = new Random().nextLong(); //To be able to match UserAgent userAgent = (UserAgent) getContext().getMainAgent(); // take username as default name String name = userAgent.getLoginName(); System.out.println("User name : " + name); if (name.equals("anonymous")) { return unauthorizedMessage(); } L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_9, "" + randomLong); JSONObject objResponse = new JSONObject(); String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot update repository. Cannot parse json data into string"); //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // if(!initializeDBConnection()){ // objResponse.put("message", "Cannot connect to database"); // L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); // return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); // } JSONObject obj; String originRepositoryName; String newRepositoryName; String fileContent; String appId; String epURL; String aopScript; try { obj = (JSONObject) JSONValue.parseWithException(content); originRepositoryName = stringfromJSON(obj, "originRepositoryName"); newRepositoryName = stringfromJSON(obj, "newRepositoryName"); //fileContent = stringfromJSON(obj,"fileContent"); appId = stringfromJSON(obj, "appId"); epURL = stringfromJSON(obj, "epURL"); aopScript = stringfromJSON(obj, "aopScript"); } catch (ParseException e) { e.printStackTrace(); objResponse.put("message", "Cannot update repository. Cannot parse json data into string. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot update repository. Cannot parse json data into string. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // check if repo exist TreeWalk treeWalk = null; Repository newRepository = null; Repository originRepository = null; // helper variables // variables holding content to be modified and added to repository later String widget = null; try { RepositoryHelper.deleteRemoteRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); } catch (GitHubException e) { //e.printStackTrace(); } try { PersonIdent caeUser = new PersonIdent(gitHubUserNewRepo, gitHubUserMailNewRepo); originRepository = RepositoryHelper.getRemoteRepository(originRepositoryName, gitHubOrganizationOrigin); newRepository = RepositoryHelper.generateNewRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); File originDir = originRepository.getDirectory(); // now load the TreeWalk containing the origin repository content treeWalk = RepositoryHelper.getRepositoryContent(originRepositoryName, gitHubOrganizationOrigin); //System.out.println("PATH " + treeWalk.getPathString()); System.out.println("PATH2 " + originDir.getParent()); System.out.println("PATH3 " + newRepository.getDirectory().getParent()); // treeWalk.setFilter(PathFilter.create("frontend/")); ObjectReader reader = treeWalk.getObjectReader(); // walk through the tree and retrieve the needed templates while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = reader.open(objectId); switch (treeWalk.getNameString()) { case "widget.xml": widget = new String(loader.getBytes(), "UTF-8"); break; } } // replace widget.xml //widget = createWidgetCode(widget, htmlElementTemplate, yjsImports, gitHubOrganization, repositoryName, frontendComponent); widget = RepositoryHelper.appendWidget(widget, gitHubOrganizationNewRepo, newRepositoryName); RepositoryHelper.copyFolder(originRepository.getDirectory().getParentFile(), newRepository.getDirectory().getParentFile()); String aopfilestring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/aop.pack.js", Charset.forName("UTF-8")); String oidcwidgetfilestring = RepositoryHelper .readFile("../GamificationGamifierService/jsfiles/oidc-widget.js", Charset.forName("UTF-8")); String gamifierstring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/gamifier.js", Charset.forName("UTF-8")); gamifierstring = gamifierstring.replace("$Application_Id$", appId); gamifierstring = gamifierstring.replace("$Endpoint_URL$", epURL); gamifierstring = gamifierstring.replace("$AOP_Script$", aopScript); // add files to new repository newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "", "widget.xml", widget); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "aop.pack.js", aopfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "oidc-widget.js", oidcwidgetfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "gamifier.js", gamifierstring); // stage file Git.wrap(newRepository).add().addFilepattern(".").call(); // commit files Git.wrap(newRepository).commit().setMessage("Generated new repo ").setCommitter(caeUser).call(); // push (local) repository content to GitHub repository "gh-pages" branch RepositoryHelper.pushToRemoteRepository(newRepository, gitHubUserNewRepo, gitHubPasswordNewRepo, "master", "gh-pages"); // close all open resources } catch (GitHubException e1) { // TODO Auto-generated catch block e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (Exception e) { objResponse.put("message", "Cannot update repository. Github exception. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { newRepository.close(); originRepository.close(); treeWalk.close(); } objResponse.put("message", "Updated"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_22, "" + appId); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_23, "" + name); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Checks if a resource is reachable.//from www . j av a 2 s. c o m * * @param uri the uri * @return true, if is reachable */ public static boolean isReachable(String uri) { try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection(); myURLConnection.setRequestMethod("HEAD"); return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java
private List<Point> getServerData() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); HttpURLConnection urlConnection = (HttpURLConnection) new URL(findNumericMetricsUrl).openConnection(); urlConnection.connect();//from w w w.j ava 2 s . c o m int responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { String msg = "Could not get metrics list from server: %s, %d"; fail(String.format(Locale.ROOT, msg, findNumericMetricsUrl, responseCode)); } List<String> metricNames; try (InputStream inputStream = urlConnection.getInputStream()) { TypeFactory typeFactory = objectMapper.getTypeFactory(); CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricName.class); List<MetricName> value = objectMapper.readValue(inputStream, valueType); metricNames = value.stream().map(MetricName::getId).collect(toList()); } Stream<Point> points = Stream.empty(); for (String metricName : metricNames) { String[] split = metricName.split("\\."); String type = split[split.length - 1]; urlConnection = (HttpURLConnection) new URL(findNumericDataUrl(metricName)).openConnection(); urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { fail("Could not load metric data from server: " + responseCode); } try (InputStream inputStream = urlConnection.getInputStream()) { TypeFactory typeFactory = objectMapper.getTypeFactory(); CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricData.class); List<MetricData> data = objectMapper.readValue(inputStream, valueType); Stream<Point> metricPoints = data.stream() .map(metricData -> new Point(type, metricData.timestamp, metricData.value)); points = Stream.concat(points, metricPoints); } } return points.sorted(Comparator.comparing(Point::getType).thenComparing(Point::getTimestamp)) .collect(toList()); }