Esempio n. 1
0
  protected String getData(
      String url, String method, String contentType, String content, ContinuationToken cTokens) {
    try {
      HttpClient client = new DefaultHttpClient();
      HttpResponse res = null;
      url = url.replaceAll(" ", "%20");
      if (method == "GET") {
        HttpGet get = new HttpGet(url);
        get.addHeader("Authorization", token);
        get.addHeader("Content-Type", contentType);
        get.addHeader("Content-Length", content.length() + "");
        res = client.execute(get);
      } else if (method == "POST") {
        HttpPost post = new HttpPost(url);
        post.addHeader("Authorization", token);
        post.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        post.setEntity(entity);
        res = client.execute(post);
      } else if (method == "DELETE") {
        HttpDelete del = new HttpDelete(url);
        del.addHeader("Authorization", token);
        del.addHeader("Content-Type", contentType);
        res = client.execute(del);
      } else if (method == "PUT") {
        HttpPut put = new HttpPut(url);
        put.addHeader("Authorization", token);
        put.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        put.setEntity(entity);
        res = client.execute(put);
      }
      StatusLine sl = res.getStatusLine();
      String json = "";
      if (sl.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        res.getEntity().writeTo(out);
        out.close();
        json = out.toString();
        Log.i("result", json);
        return json;
      } else {
        Log.i("error", sl.getReasonPhrase());
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }
  public boolean deleteRequest(String path) {
    log.info("deleteRequest(" + path + ")");
    // http://msdn.microsoft.com/en-us/library/windowsazure/dn151676.aspx
    HttpDelete httpDelete = new HttpDelete(getAPIEndPoint(path));
    httpDelete.addHeader("Authorization", this.getToken());
    httpDelete.addHeader("Content-Type", "application/json");
    httpDelete.addHeader("DataServiceVersion", "3.0;NetFx");
    httpDelete.addHeader("MaxDataServiceVersion", "3.0;NetFx");

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {
      HttpResponse response = httpClient.execute(httpDelete);
      HttpEntity entity = response.getEntity();

      if (response.getStatusLine().getStatusCode() != 204) {
        log.error("An error occured when deleting an object in Office 365");
        this.invalidateToken();
        StringBuffer sb = new StringBuffer();
        if (entity != null && entity.getContent() != null) {
          BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
          String s = null;

          log.info("Response :{0}", response.getStatusLine().toString());

          while ((s = in.readLine()) != null) {
            sb.append(s);
            log.info(s);
          }
        }
        throw new ConnectorException(
            "Delete Object failed to "
                + path
                + ". Error code was "
                + response.getStatusLine().getStatusCode()
                + ". Received the following response "
                + sb.toString());
      } else {
        return true;
      }
    } catch (ClientProtocolException cpe) {
      log.error(cpe, "Error doing deleteRequest to path {0}", path);
      throw new ConnectorException("Exception whilst doing DELETE to " + path);
    } catch (IOException ioe) {
      log.error(ioe, "IOE Error doing deleteRequest to path {0}", path);
      throw new ConnectorException("Exception whilst doing DELETE to " + path);
    }
  }
  public DrvLicRepresentation cancel() {
    try {
      HttpDelete request = new HttpDelete(link.getHref());
      request.addHeader("Accept", DrvLicRepresentation.DRVLIC_MEDIA_TYPE);

      log.debug("calling {} {}", request.getMethod(), request.getURI());
      HttpResponse response = httpClient.execute(request);
      result = HttpResult.getResult(Void.class, null, response);
      if (result.status >= 200 && result.status <= 299) {
        return new DrvLicRepresentation(); // no links
      } else {
        log.warn(
            String.format(
                "error calling %s %s, %d:%s",
                request.getMethod(), link, result.status, result.errorMsg));
        return null;
      }
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException(ex);
    } catch (IllegalStateException ex) {
      ex.printStackTrace();
      throw new RuntimeException("State error reading stream", ex);
    } catch (IOException ex) {
      ex.printStackTrace();
      throw new RuntimeException("IO error reading stream", ex);
    } catch (JAXBException ex) {
      ex.printStackTrace();
      throw new RuntimeException("JAXB error demarshalling result", ex);
    } finally {
    }
  }
Esempio n. 4
0
  public static String delete(String url, Map<String, String> data)
      throws IllegalStateException, ClientProtocolException, HttpResponseException, IOException {
    HttpDelete request = null;

    if (data == null || data.isEmpty()) {
      request = new HttpDelete(url);
    } else {
      String paramStr = "";
      for (Map.Entry<String, String> entry : data.entrySet()) {
        paramStr += "&" + entry.getKey() + "=" + entry.getValue();
      }

      if (url.indexOf("?") == -1) {
        url += paramStr.replaceFirst("&", "?");
      } else {
        url += paramStr;
      }
      url += "&";
      url = encodeSpecCharacters(url);
      L.e(url);
      request = new HttpDelete(url);
    }
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    // support Gzip
    supportGzip(request);
    return processResponse(httpClient.execute(request));
  }
Esempio n. 5
0
  /**
   * Synchroniseert verwijderde polygonen met de server
   *
   * @param group groupid om polygonen uit te syncen
   * @throws SyncException
   */
  private void deletePolygons(int group) throws SyncException {
    Cursor c = db.getRemovedPolygons(group);
    int polygonid = 0;

    if (!c.moveToFirst()) {
      return; // Niks te syncen, dus gelijk klaar!
    }

    do {
      polygonid = c.getInt(0);

      HttpDelete httpd = new HttpDelete(serverUrl + "polygon/id/" + polygonid);
      UsernamePasswordCredentials creds = new UsernamePasswordCredentials(mappUser, mappPass);

      try {
        httpd.addHeader(new BasicScheme().authenticate(creds, httpd));
      } catch (AuthenticationException e1) {
        Log.e(Mapp.TAG, e1.getStackTrace().toString());
        throw new SyncException("Authentication failed");
      }

      HttpResponse response;

      try {
        response = httpclient.execute(httpd);

        if (response.getStatusLine().getStatusCode() == 418) {
          throw new SyncException("Unable to synchronize because the server is a teapot.");
        } else if (response.getStatusLine().getStatusCode() == 401) {
          throw new SyncException("Not authorized");
        } else if (response.getStatusLine().getStatusCode() != 200) {
          // Er is iets mis gegaan.
          // Lees de uitvoer
          InputStream is = response.getEntity().getContent();
          BufferedReader r = new BufferedReader(new InputStreamReader(is));
          StringBuilder total = new StringBuilder();
          String line;
          while ((line = r.readLine()) != null) {
            total.append(line);
          }

          JSONObject result = null;
          result = new JSONObject(total.toString());
          Log.e(Mapp.TAG, "Sync error: " + result.getString("message"));
          throw new SyncException(result.getString("message"));
        } else {
          db.removeRemovedPolygon(polygonid);
        }
      } catch (ClientProtocolException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Epic HTTP failure");
      } catch (IOException e) {
        Log.e(Mapp.TAG, e.getMessage());
        throw new SyncException("Exception during server synchronisation");
      } catch (JSONException e) {
        Log.e(Mapp.TAG, "Sync failed. Getting status message from JSON response failed.");
        throw new SyncException("Invalid server response");
      }
    } while (c.moveToNext());
  }
 /*.................................................................................................................*/
 public void deleteJob(HttpClient httpclient, String URL) {
   HttpDelete httpdelete = new HttpDelete(URL);
   httpdelete.addHeader("cipres-appkey", CIPRESkey);
   try {
     HttpResponse response = httpclient.execute(httpdelete);
   } catch (IOException e) {
     Debugg.printStackTrace(e);
   }
 }
 @Test
 public void testDeleteVipCustomer() throws Exception {
   HttpDelete delete =
       new HttpDelete(
           "http://localhost:" + PORT_PATH + "/rest/customerservice/customers/vip/gold/123");
   delete.addHeader("Accept", "text/xml");
   HttpResponse response = httpclient.execute(delete);
   assertEquals(200, response.getStatusLine().getStatusCode());
 }
Esempio n. 8
0
  // TODO: throw all exceptions in the Execute method (or equivalent)
  public void Execute(int method) throws UnsupportedEncodingException {
    last_method = method;
    switch (method) {
      case HTTP_GET:
        {
          HttpGet request = new HttpGet(url + getCombinedParams());
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }
          executeRequest(request, url);
          break;
        }
      case HTTP_POST:
        {
          HttpPost request = new HttpPost(url);
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case HTTP_PUT:
        {
          HttpPut request = new HttpPut(url);
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case HTTP_DELETE:
        {
          HttpDelete request = new HttpDelete(url + getCombinedParams());
          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }
          executeRequest(request, url);
          break;
        }
    }
  }
  public HttpResponse doDelete(URI resourcePath) throws Exception {
    HttpDelete httpDelete = null;
    try {
      httpDelete = new HttpDelete(resourcePath);
      httpDelete.addHeader("Content-Type", "application/json");

      return httpClient.execute(httpDelete, new HttpResponseHandler());
    } finally {
      releaseConnection(httpDelete);
    }
  }
Esempio n. 10
0
 @SuppressWarnings("unused")
 private synchronized void doUnRegister(String service) {
   String url = registryURL;
   try {
     HttpDelete method = new HttpDelete(url);
     method.addHeader("service", service);
     ResponseHandler<String> handler = new BasicResponseHandler();
     String responseBody = httpClient.execute(method, handler);
     LOG.debug("DELETE to " + url + " got a " + responseBody);
   } catch (Exception e) {
     LOG.debug("DELETE to " + url + " failed with: " + e);
   }
 }
Esempio n. 11
0
  public static void deleteMessage(String login, String id) {
    HttpClient m_ClientHttp = new DefaultHttpClient();
    try {

      URI uri = new URI("https", WEB.URL, WEB.DELETE_MESSAGE(login, id), null, null);
      HttpDelete requeteDelete = new HttpDelete(uri);
      requeteDelete.addHeader("Content-Type", "application/json");

      String body = m_ClientHttp.execute(requeteDelete, new BasicResponseHandler());
    } catch (Exception e) {
      throw new IllegalArgumentException(e.getMessage());
    }
  }
Esempio n. 12
0
  /**
   * Deletes OAuth Client from Authorization Server.
   *
   * @param consumerKey consumer key of the OAuth Client.
   * @throws APIManagementException
   */
  @Override
  public void deleteApplication(String consumerKey) throws APIManagementException {

    LOGGER.log(
        Level.INFO, "OAuthTwoClient - deleteApplication: " + consumerKey + " will be deleted.");

    Long id = nameIdMapping.get(consumerKey);

    String configURL = configuration.getParameter(OAuthTwoConstants.CLIENT_REG_ENDPOINT);
    String configURLsAccessToken =
        configuration.getParameter(OAuthTwoConstants.REGISTRAION_ACCESS_TOKEN);
    HttpClient client = getHttpClient();

    try {

      // Deletion has to be called providing the ID. If we don't have the
      // ID we can't proceed with Delete.
      if (id != null) {
        configURL += "/" + id.toString();
        HttpDelete httpDelete = new HttpDelete(configURL);

        LOGGER.log(
            Level.INFO, "OAuthTwoClient - deleteApplication: id:" + id + " URL:" + configURL);

        // Set Authorization Header
        httpDelete.addHeader(
            OAuthTwoConstants.AUTHORIZATION, OAuthTwoConstants.BEARER + configURLsAccessToken);
        HttpResponse response = client.execute(httpDelete);
        int responseCode = response.getStatusLine().getStatusCode();
        LOGGER.log(Level.INFO, "Delete application response code :  " + responseCode);
        if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_NO_CONTENT) {
          LOGGER.log(
              Level.INFO,
              "OAuth Client for consumer Id " + consumerKey + " has been successfully deleted");
          nameIdMapping.remove(consumerKey);
        } else {
          handleException("Problem occurred while deleting client for Consumer Key " + consumerKey);
        }
      }

    } catch (IOException e) {
      handleException("Error while reading response body from Server ", e);
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Esempio n. 13
0
  @Override
  public String delete(String token, String said) throws ServiceNotAvailableException {
    HttpDelete httpDelete = new HttpDelete(serviceEnpoint + "?said=" + said);
    String encode = Base64.encodeBase64String((said + ":" + token).getBytes());
    httpDelete.addHeader("Authorization", "Basic " + encode.replace("\r\n", ""));

    HttpResponse response;
    try {
      response = httpClient.execute(httpDelete);

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        String jsonResponse = IOUtils.toString(entity.getContent());
        logger.debug("Register response: {}", jsonResponse);
        return jsonResponse;
      }
    } catch (Exception e) {
      throw new ServiceNotAvailableException("Unable to register");
    }
    return null;
  }
Esempio n. 14
0
  @Override
  public String deleteGet(String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    StringBuffer responseOutput = new StringBuffer();
    try {
      HttpDelete request = new HttpDelete(url);
      request.addHeader("content-type", "application/json");
      HttpResponse response = httpClient.execute(request);
      responseCode = response.getStatusLine().getStatusCode();

      if (responseCode == 200 || responseCode == 204) {
        if (response.getEntity() != null) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

          String output;
          while ((output = br.readLine()) != null) {
            responseOutput.append(output);
          }
        }
      } else {
        logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        throw new RuntimeException(
            "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
      }

    } catch (Exception ex) {
      logger.error("exception for url = " + url);
      logger.error(elog.toStringException(ex));
    } finally {
      httpClient.getConnectionManager().shutdown();
    }

    if (responseCode == -1) {
      return "Exception";
    }
    return responseOutput.toString();
  }
Esempio n. 15
0
  public String delete(String url, Map<String, String> headers)
      throws ClientProtocolException, IOException, AuthorizationDeniedException {
    // create request
    HttpDelete request = new HttpDelete(url);

    if (logger.isDebugEnabled()) {
      logger.debug("getting url: " + url);
    }

    // add headers to request
    if (headers != null && headers.size() > 0) {
      for (String header : headers.keySet()) {
        String value = headers.get(header);
        request.addHeader(header, value);

        if (logger.isDebugEnabled()) {
          logger.debug("adding header: " + header + " = " + value);
        }
      }
    }

    return process(request);
  }
  /* Delete the file used to test savePhoto() after the testcase has run */
  public void tearDown() throws Exception {

    /* Delete the story added to online */
    @SuppressWarnings("resource")
    HttpClient httpclient = new DefaultHttpClient();
    HttpDelete httpDelete =
        new HttpDelete("http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + 100);
    httpDelete.addHeader("Accept", "application/json");

    HttpResponse response = httpclient.execute(httpDelete);

    String status = response.getStatusLine().toString();
    System.out.println(status);

    HttpEntity entity = response.getEntity();
    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
    String output;
    System.err.println("Output from Server -> ");
    while ((output = br.readLine()) != null) {
      System.err.println(output);
    }
    testActivity.getApplicationContext().deleteFile("Download15");
  }
 @Override
 public void deleteContent(URI uri) throws IOException {
   HttpDelete httpDelete = new HttpDelete(uri);
   httpDelete.addHeader("Authorization", "OAuth2 " + tokenClient.getAccessToken());
   httpClient.execute(httpDelete);
 }
 public void doDelete(String url) throws ClientProtocolException, IOException {
   HttpClient httpclient = new DefaultHttpClient();
   HttpDelete delete = new HttpDelete(url);
   delete.addHeader("accept", "application/json");
   httpclient.execute(delete);
 }
  public void execute(RequestMethod method) throws Exception {
    switch (method) {
      case GET:
        {
          // add parameters
          String allParams = "";
          if (!params.isEmpty()) {
            allParams += "?";
            for (NameValuePair param : params) {
              String paramString =
                  param.getName() + "=" + URLEncoder.encode(param.getValue(), "UTF-8");
              if (allParams.length() > 1) {
                allParams += "&" + paramString;
              } else {
                allParams += paramString;
              }
            }
          }

          HttpGet request = new HttpGet(url + allParams);

          // add headers
          for (NameValuePair header : headers) {
            request.addHeader(header.getName(), header.getValue());
          }

          executeRequest(request, url);
          break;
        }
      case POST:
        {
          HttpPost request = new HttpPost(url);

          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case PUT:
        {
          HttpPut request = new HttpPut(url);

          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case DELETE:
        {
          // add parameters
          String allParams = "";
          if (!params.isEmpty()) {
            allParams += "?";
            for (NameValuePair param : params) {
              String paramString =
                  param.getName() + "=" + URLEncoder.encode(param.getValue(), "UTF-8");
              if (allParams.length() > 1) {
                allParams += "&" + paramString;
              } else {
                allParams += paramString;
              }
            }
          }

          HttpDelete request = new HttpDelete(url + allParams);

          // add headers
          for (NameValuePair header : headers) {
            request.addHeader(header.getName(), header.getValue());
          }

          executeRequest(request, url);
          break;
        }
    }
  }