示例#1
0
  public String readInfo() {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://androides.herokuapp.com/friends.json");
    try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(MainActivity.class.toString(), "Error al descargar json");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
示例#2
0
文件: Cosm.java 项目: nuest/JCosmAPI
 /**
  * Get a feed object by its feed identifier
  *
  * @param feedid Id of the Cosm feed to retrieve
  * @return Feed object which corresponds to the id provided as the parameter
  * @throws CosmException If something goes wrong, or if the Feed was not found.
  */
 public Feed getFeed(int feedid, boolean show_user) throws CosmException {
   try {
     HttpGet hr = null;
     if (show_user) {
       hr =
           new HttpGet(
               API_BASE_URL_V2
                   + API_RESOURCE_FEEDS
                   + "/"
                   + feedid
                   + JSON_FILE_EXTENSION
                   + "?show_user=true");
     } else {
       hr =
           new HttpGet(
               API_BASE_URL_V2
                   + API_RESOURCE_FEEDS
                   + "/"
                   + feedid
                   + JSON_FILE_EXTENSION
                   + "?show_user=false");
     }
     HttpResponse response = this.client.execute(hr);
     StatusLine statusLine = response.getStatusLine();
     String body = this.client.getBody(response);
     if (statusLine.getStatusCode() == 200) {
       return CosmFactory.toFeed(body);
     }
     throw new CosmException(statusLine, body);
   } catch (IOException e) {
     throw new CosmException(IO_EXCEPTION_MESSAGE);
   }
 }
示例#3
0
    @Override
    protected JSONArray doInBackground(Map<String, String>... uri) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
      JSONArray finalResult = null;
      try {
        response = httpclient.execute(new HttpGet(uri[0].get("host")));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

          BufferedReader reader =
              new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
          String json = reader.readLine();
          JSONTokener tokener = new JSONTokener(json);
          try {
            finalResult = new JSONArray(tokener);
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

        } else {
          // Closes the connection.
          response.getEntity().getContent().close();
          throw new IOException(statusLine.getReasonPhrase());
        }
      } catch (ClientProtocolException e) {
        // TODO Handle problems..
      } catch (IOException e) {
        // TODO Handle problems..
      }
      return finalResult;
    }
示例#4
0
文件: Cosm.java 项目: nuest/JCosmAPI
 // create datapoint
 public void createDatapoint(Integer feedid, String datastreamid, Datapoint datapoint)
     throws CosmException {
   try {
     HttpPost request =
         new HttpPost(
             API_BASE_URL_V2
                 + API_RESOURCE_FEEDS
                 + "/"
                 + feedid
                 + "/datastreams/"
                 + datastreamid
                 + "/datapoints"
                 + JSON_FILE_EXTENSION);
     JSONObject jo = new JSONObject();
     JSONArray ja = new JSONArray();
     ja.put(datapoint.toJSONObject());
     jo.put("datapoints", ja);
     request.setEntity(new StringEntity(jo.toString()));
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     this.client.getBody(response);
     if (statusLine.getStatusCode() != 200) {
       throw new CosmException(response.getStatusLine().toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException("Caught exception in create datapoint" + e.getMessage());
   }
 }
示例#5
0
文件: Cosm.java 项目: nuest/JCosmAPI
  // update datapoint
  // Cosm documentation says, it's a post. It is in fact a PUT
  public void updateDatapoint(Integer feedid, String datastreamid, Datapoint datapoint)
      throws CosmException {
    try {
      HttpPut request =
          new HttpPut(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints/"
                  + datapoint.getAt()
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("value", datapoint.getValue());
      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      String body = this.client.getBody(response);
      if (statusLine.getStatusCode() != 200) {
        if (body.length() > 0) {
          JSONObject ej = new JSONObject(body);
          throw new CosmException(ej.getString("errors"));
        }

        throw new CosmException(statusLine.toString());
      }
    } catch (Exception e) {
      throw new CosmException("Caught exception in update datapoint: " + e.getMessage());
    }
  }
示例#6
0
  // 底层请求打印页面
  private byte[] sendRequest(HttpRequestBase request) throws Exception {
    CloseableHttpResponse response = httpclient.execute(request);

    // 设置超时
    setTimeOut(request, 5000);

    // 获取返回的状态列表
    StatusLine statusLine = response.getStatusLine();
    System.out.println("StatusLine : " + statusLine);

    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      try {
        // 获取response entity
        HttpEntity entity = response.getEntity();
        System.out.println("getContentType : " + entity.getContentType().getValue());
        System.out.println("getContentEncoding : " + entity.getContentEncoding().getValue());

        // 读取响应内容
        byte[] responseBody = EntityUtils.toByteArray(entity);

        // 关闭响应流
        EntityUtils.consume(entity);
        return responseBody;
      } finally {
        response.close();
      }
    }
    return null;
  }
示例#7
0
文件: Cosm.java 项目: nuest/JCosmAPI
  // create datastream
  public Datastream createDatastream(Integer feedid, Datastream datastream) throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("version", Cosm.VERSION);

      JSONArray ja = new JSONArray();
      ja.put(datastream.toJSONObject());
      jo.put("datastreams", ja);

      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 201) {
        String a[] = response.getHeaders(HEADER_PARAM_LOCATION)[0].getValue().split("/");
        String datastreamid = a[a.length - 1];
        this.client.getBody(response);
        return this.getDatastream(feedid, datastreamid);
      }

      throw new HttpException(response.getStatusLine().toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException("Caught exception in create Datastream" + e.getMessage());
    }
  }
示例#8
0
  @Override
  protected Void doInBackground(Void... params) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPostRequest = new HttpPost(url);

    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("data", request));

      httpPostRequest.setHeader("Content-type", "application/x-www-form-urlencoded");
      httpPostRequest.setHeader("Accept", "application/json");
      httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpResponse response = httpClient.execute(httpPostRequest);
      StatusLine status = response.getStatusLine();
      Log.v("Status response", status.getStatusCode() + "");

      HttpEntity entity = response.getEntity();

      if (entity != null) {
        InputStream inputStream = entity.getContent();
        responseResult = convertStreamToString(inputStream);
        inputStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      responseResult = "";
    }

    return null;
  }
  private void putUrlFile(String url, DefaultHttpClient httpClient, String content)
      throws NotFoundException, ReportableError {
    try {
      HttpPut httpPut = new HttpPut(url);
      httpPut.setEntity(new StringEntity(content, "UTF-8"));
      HttpResponse response = httpClient.execute(httpPut);
      StatusLine statResp = response.getStatusLine();
      int statCode = statResp.getStatusCode();
      if (statCode >= 400) {
        this.pushedStageFile = false;
        throw new ReportableError(
            r.getString(
                R.string.error_url_put_detail,
                url,
                "Server returned code: " + Integer.toString(statCode)),
            null);
      } else {
        this.pushedStageFile = true;
      }

      httpClient.getConnectionManager().shutdown();
    } catch (UnsupportedEncodingException e) {
      throw new ReportableError(
          r.getString(R.string.error_unsupported_encoding, "mobileorg.org"), e);
    } catch (IOException e) {
      throw new ReportableError(r.getString(R.string.error_url_put, url), e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public ClientResponse apply(ClientRequest jerseyRequest) {
    try {
      final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
      final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);

      final StatusLine statusLine = apacheResponse.getStatusLine();
      final Response.StatusType status =
          Statuses.from(statusLine.getStatusCode(), firstNonNull(statusLine.getReasonPhrase(), ""));

      final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
      for (Header header : apacheResponse.getAllHeaders()) {
        final List<String> headerValues = jerseyResponse.getHeaders().get(header.getName());
        if (headerValues == null) {
          jerseyResponse.getHeaders().put(header.getName(), Lists.newArrayList(header.getValue()));
        } else {
          headerValues.add(header.getValue());
        }
      }

      final HttpEntity httpEntity = apacheResponse.getEntity();
      jerseyResponse.setEntityStream(
          httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0]));

      return jerseyResponse;
    } catch (Exception e) {
      throw new ProcessingException(e);
    }
  }
  public HttpClient getMockHttpClient() {
    HttpClient mock = Mockito.mock(HttpClient.class);
    HttpParams paramsMock = Mockito.mock(HttpParams.class);
    ClientConnectionManager connectionMock = Mockito.mock(ClientConnectionManager.class);
    HttpResponse hrMocked = Mockito.mock(HttpResponse.class);
    StatusLine slMocked = Mockito.mock(StatusLine.class);

    Header headerMocked = Mockito.mock(Header.class);

    Mockito.when(connectionMock.getSchemeRegistry())
        .thenReturn(SchemeRegistryFactory.createDefault());
    Mockito.when(hrMocked.getEntity()).thenReturn(heMocked);
    Mockito.when(mock.getParams()).thenReturn(paramsMock);
    Mockito.when(mock.getConnectionManager()).thenReturn(connectionMock);
    try {
      Mockito.when(mock.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)))
          .thenReturn(hrMocked);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Mockito.when(hrMocked.getStatusLine()).thenReturn(slMocked);
    Mockito.when(slMocked.getStatusCode()).thenReturn(200);
    Mockito.when(heMocked.getContentType()).thenReturn(headerMocked);
    Mockito.when(headerMocked.getElements()).thenReturn(new HeaderElement[0]);
    return mock;
  }
示例#12
0
  protected JsonResponse extractJsonResponse(HttpResponse httpResponse) throws EtcdClientException {
    try {
      StatusLine statusLine = httpResponse.getStatusLine();
      int statusCode = statusLine.getStatusCode();

      String json = null;

      if (httpResponse.getEntity() != null) {
        try {
          json = EntityUtils.toString(httpResponse.getEntity());
        } catch (IOException e) {
          throw new EtcdClientException("Error reading response", e);
        }
      }

      if (statusCode != 200) {
        if (statusCode == 400 && json != null) {
          // More information in JSON
        } else {
          throw new EtcdClientException(
              "Error response from etcd: " + statusLine.getReasonPhrase(), statusCode);
        }
      }

      return new JsonResponse(json, statusCode);
    } finally {
      close(httpResponse);
    }
  }
示例#13
0
  protected StatusLine mockStatusLine() {
    StatusLine statusLine = Mockito.mock(StatusLine.class);

    Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);

    return statusLine;
  }
  public String getRapLeafRequest() {
    String firstName = "";
    String lastName = "";
    String beforeAt = "";
    String afterAt = "";
    EditText setFirstName = (EditText) findViewById(R.id.name_form); // gets name from form
    firstName = setFirstName.getEditableText().toString();
    int spaceIndex = 0;
    if (firstName.contains(" ")) spaceIndex = firstName.indexOf(" ");
    Log.v(DEBUG_TAG, "spaceIdx: " + spaceIndex);
    lastName = firstName.substring(spaceIndex + 1); // parses name
    firstName = firstName.substring(0, spaceIndex);
    Log.v(DEBUG_TAG, "First Name = " + firstName);
    Log.v(DEBUG_TAG, "Last Name = " + lastName);
    EditText setEmail = (EditText) findViewById(R.id.email_form); // gets email from form
    beforeAt = setEmail.getEditableText().toString();
    int atIndex = 0; // parses email
    if (beforeAt.contains("@")) atIndex = beforeAt.indexOf("@");
    else Log.v(DEBUG_TAG, "not a valid email address");
    afterAt = beforeAt.substring(atIndex + 1);
    beforeAt = beforeAt.substring(0, atIndex);
    Log.v(DEBUG_TAG, "beforeAt =" + beforeAt);
    Log.v(DEBUG_TAG, "afterAt =" + afterAt);
    String url =
        "https://personalize.rapleaf.com/v4/dr?first="
            + firstName
            + "&last="
            + lastName
            + "&email="
            + beforeAt
            + "%40"
            + afterAt
            + "&api_key=7e67d0b8103f766d9333abd7e7ee6c5f";
    // builds the HTTP address
    StringBuilder builder = new StringBuilder();
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse response = httpclient.execute(httpGet);
      StatusLine statusline = response.getStatusLine();
      int statusCode = statusline.getStatusCode();
      if (statusCode == 200) { // no error
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.v(DEBUG_TAG, "Failed to download");
      }

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
示例#15
0
 @Override
 public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
   final URI uri = root.resolve("./" + key.getHashCode());
   HttpGet httpGet = new HttpGet(uri);
   CloseableHttpResponse response = null;
   try {
     response = httpClient.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug("Response for GET {}: {}", uri, statusLine);
     }
     int statusCode = statusLine.getStatusCode();
     if (statusCode >= 200 && statusCode < 300) {
       reader.readFrom(response.getEntity().getContent());
       return true;
     } else if (statusCode == 404) {
       return false;
     } else {
       throw new BuildCacheException(
           String.format(
               "HTTP cache returned status %d: %s for key '%s' from %s",
               statusCode, statusLine.getReasonPhrase(), key, getDescription()));
     }
   } catch (IOException e) {
     throw new BuildCacheException(
         String.format("loading key '%s' from %s", key, getDescription()), e);
   } finally {
     HttpClientUtils.closeQuietly(response);
   }
 }
  /**
   * Do request and validate response
   *
   * @param httpClientToTest
   * @param url
   * @param expectedTitle
   */
  private void validateResponseToRequest(
      HttpClient httpClientToTest, String url, String expectedTitle) throws Exception {
    HttpGet request = new HttpGet(url);
    HttpResponse response = httpClientToTest.execute(request);

    logger.info("request:" + request);

    StatusLine status = response.getStatusLine();
    Assert.assertEquals("Status code:" + status, HttpStatus.SC_OK, status.getStatusCode());
    logger.info(status);

    BasicResponseHandler responseHandler = new BasicResponseHandler();
    String responseBody = responseHandler.handleResponse(response).trim();
    final int xmlstart = responseBody.indexOf("<?xml");
    if (xmlstart > 0) {
      responseBody = responseBody.substring(xmlstart);
    }
    logger.debug("responseBody*>>");
    logger.debug(responseBody);
    logger.debug("responseBody*<<");

    Pattern titlePattern = Pattern.compile("(<title>)([^<]+)(</title>)");
    Matcher matcher = titlePattern.matcher(responseBody);
    Assert.assertTrue("title element found", matcher.find());

    String title = matcher.group(2);
    Assert.assertEquals("title", expectedTitle, title);
  }
示例#17
0
    private void sendMessage(final String suffix, final HttpEntity message) throws SenderException {
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
      HttpConnectionParams.setSoTimeout(httpParams, 5000);
      HttpClient httpClient = new DefaultHttpClient(httpParams);

      HttpPost httppost = new HttpPost(url + "/" + suffix + "/" + buildId);
      if (message != null) {
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf");
        httppost.setEntity(message);
      }
      if (!secret.isEmpty()) {
        httppost.setHeader(DASH_SECRET_HEADER, secret);
      }
      StatusLine status;
      try {
        status = httpClient.execute(httppost).getStatusLine();
      } catch (IOException e) {
        throw new SenderException("Error sending results to " + url, e);
      }
      if (status.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new SenderException(
            "Permission denied while sending results to "
                + url
                + ". Did you specified --dash_secret?");
      }
    }
 protected RetsHttpResponse execute(final HttpRequestBase method, Map<String, String> headers)
     throws RetsException {
   try {
     // add the default headers
     if (this.defaultHeaders != null) {
       for (Map.Entry<String, String> entry : this.defaultHeaders.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // add our request headers from rets
     if (headers != null) {
       for (Map.Entry<String, String> entry : headers.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // optional ua-auth stuff here
     if (this.userAgentPassword != null) {
       method.setHeader(RETS_UA_AUTH_HEADER, calculateUaAuthHeader(method, getCookies()));
     }
     // try to execute the request
     HttpResponse response = this.httpClient.execute(method);
     StatusLine status = response.getStatusLine();
     if (status.getStatusCode() != HttpStatus.SC_OK) {
       throw new InvalidHttpStatusException(status);
     }
     return new CommonsHttpClientResponse(response, getCookies());
   } catch (Exception e) {
     throw new RetsException(e);
   }
 }
  /**
   * Fetches user's e-mail - only public for testing.
   *
   * @param allToks OAuth tokens.
   * @param httpClient The HTTP client.
   */
  public int fetchEmail(final Map<String, String> allToks, final HttpClient httpClient) {
    final String endpoint = "https://www.googleapis.com/oauth2/v1/userinfo";
    final String accessToken = allToks.get("access_token");
    final HttpGet get = new HttpGet(endpoint);
    get.setHeader(HttpHeaders.Names.AUTHORIZATION, "Bearer " + accessToken);

    try {
      log.debug("About to execute get!");
      final HttpResponse response = httpClient.execute(get);
      final StatusLine line = response.getStatusLine();
      log.debug("Got response status: {}", line);
      final HttpEntity entity = response.getEntity();
      final String body = IOUtils.toString(entity.getContent(), "UTF-8");
      EntityUtils.consume(entity);
      log.debug("GOT RESPONSE BODY FOR EMAIL:\n" + body);

      final int code = line.getStatusCode();
      if (code < 200 || code > 299) {
        log.error("OAuth error?\n" + line);
        return code;
      }

      final Profile profile = JsonUtils.OBJECT_MAPPER.readValue(body, Profile.class);
      this.model.setProfile(profile);
      Events.sync(SyncPath.PROFILE, profile);
      // final String email = profile.getEmail();
      // this.model.getSettings().setEmail(email);
      return code;
    } catch (final IOException e) {
      log.warn("Could not connect to Google?", e);
    } finally {
      get.reset();
    }
    return -1;
  }
示例#20
0
 private static String queryBattle(String url) {
   StringBuilder builder = new StringBuilder();
   HttpClient client = HttpClientBuilder.create().build();
   try {
     HttpGet httpGet = new HttpGet(URIUtil.encodeQuery(url));
     HttpResponse response = client.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
       String line;
       while ((line = reader.readLine()) != null) {
         builder.append(line);
       }
     } else {
       LOGGER.error("Failed to download file");
       return null;
     }
   } catch (IOException e) {
     LOGGER.error(e);
   }
   return builder.toString();
 }
示例#21
0
文件: Cosm.java 项目: nuest/JCosmAPI
  // update datastream
  public void updateDatastream(Integer feedid, String datastreamid, Datastream datastream)
      throws CosmException {
    try {
      HttpPut request =
          new HttpPut(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + JSON_FILE_EXTENSION);
      request.setEntity(new StringEntity(datastream.toJSONObject().toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 200) {
        this.client.getBody(response);
        return;
      }

      throw new HttpException(statusLine.toString());
    } catch (Exception e) {
      throw new CosmException(e.getMessage());
    }
  }
示例#22
0
    @Override
    protected String doInBackground(String... uri) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
      String responseString = null;

      try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          response.getEntity().writeTo(out);
          out.close();
          responseString = out.toString();
        } else {
          // Closes the connection.
          response.getEntity().getContent().close();
          throw new IOException(statusLine.getReasonPhrase());
        }
      } catch (ClientProtocolException e) {
        // TODO Handle problems..
      } catch (IOException e) {
        // TODO Handle problems..
      }
      return responseString;
    }
示例#23
0
文件: Cosm.java 项目: nuest/JCosmAPI
  // create datapoints
  public void createDatapoints(Integer feedid, String datastreamid, Datapoint[] datapoints)
      throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();

      JSONArray ja = new JSONArray();
      for (int i = 0; (i < datapoints.length); i++) {
        ja.put(datapoints[i].toJSONObject());
      }
      jo.put("datapoints", ja);
      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      String body = this.client.getBody(response);
      if (statusLine.getStatusCode() != 200) {
        JSONObject ej = new JSONObject(body);
        throw new CosmException(ej.getString("errors"));
      }
    } catch (Exception e) {
      throw new CosmException("Caught exception in create datapoint" + e.getMessage());
    }
  }
示例#24
0
  /**
   * Uploads a {@code File} with PRIVATE read access.
   *
   * @param uri upload {@link URI}
   * @param contentTypeString content type
   * @param contentFile the file to upload
   * @throws IOException
   */
  public static void uploadPrivateContent(
      final URI uri, final String contentTypeString, final File contentFile) throws IOException {

    LOGGER.info(
        "uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
      throw new IOException(
          String.format(
              "An error occurred while trying to upload private file - %d: %s",
              statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info(
        "uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});
  }
示例#25
0
文件: Cosm.java 项目: nuest/JCosmAPI
  // get a datapoint
  public Datapoint getDatapoint(Integer feedid, String datastreamid, String at)
      throws CosmException {
    try {
      HttpGet request =
          new HttpGet(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints/"
                  + at
                  + JSON_FILE_EXTENSION);
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 200) {
        return CosmFactory.toDatapoint(this.client.getBody(response));
      }

      throw new HttpException(statusLine.toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException(e.getMessage());
    }
  }
示例#26
0
 @Override
 protected String doInBackground(String... data) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpResponse response;
   String responseString = null;
   try {
     response = httpclient.execute(new HttpGet(url));
     Log.e("HTTPClient", "Path = " + url);
     StatusLine statusLine = response.getStatusLine();
     if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       response.getEntity().writeTo(out);
       out.close();
       responseString = out.toString();
     } else {
       // Closes the connection.
       response.getEntity().getContent().close();
       throw new IOException(statusLine.getReasonPhrase());
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     onErrorResponse(e);
   } catch (IOException e) {
     e.printStackTrace();
     onErrorResponse(e);
   }
   return responseString;
 }
示例#27
0
  public String httpGetAPICall(String requestURL) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(requestURL);

    try {

      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(MainActivity.class.toString(), "Failedet JSON object");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
  /**
   * @param httppost A well-formed {@link HttpUriRequest}
   * @param owlsim An initialized {@link OWLSim} instance. It is expected that the {@link
   *     OWLGraphWrapper} is already loaded with an ontology.
   * @throws Exception
   */
  protected void runServerCommunication(HttpUriRequest httppost, OwlSim owlsim) throws Exception {
    // create server
    Server server = new Server(9031);
    server.setHandler(new OWLServer(g, owlsim));
    try {
      server.start();

      // create a client
      HttpClient httpclient = new DefaultHttpClient();

      // run request
      LOG.info("Executing=" + httppost);
      HttpResponse response = httpclient.execute(httppost);
      LOG.info("Executed=" + httpclient);

      // check response
      HttpEntity entity = response.getEntity();
      StatusLine statusLine = response.getStatusLine();
      LOG.info("Status=" + statusLine.getStatusCode());
      if (statusLine.getStatusCode() == 200) {
        String responseContent = EntityUtils.toString(entity);
        handleResponse(responseContent);
      } else {
        EntityUtils.consumeQuietly(entity);
      }
    } finally {
      // clean up
      server.stop();
    }
  }
  protected String execute(HttpRequestBase httpRequestBase)
      throws CredentialException, IOException {

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
      if (_closeableHttpClient == null) {
        afterPropertiesSet();
      }

      HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase);

      StatusLine statusLine = httpResponse.getStatusLine();

      if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {

        if (_logger.isWarnEnabled()) {
          _logger.warn("Status code " + statusLine.getStatusCode());
        }

        return null;
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {

        throw new CredentialException("Not authorized to access JSON web service");
      } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {

        throw new JSONWebServiceUnavailableException("Service unavailable");
      }

      return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8);
    } finally {
      httpRequestBase.releaseConnection();
    }
  }
示例#30
0
  private boolean ExecuteSyncingProcess(
      String msg, String name, String email, String dob, String qrCode) {
    String Url =
        "http://192.168.1.117/BellyReworked1/api/UserApi/InsertNewUser/?Name="
            + name
            + "&Email="
            + email
            + "&Dob="
            + dob
            + "&QRCode="
            + qrCode;
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(Url);
    try {
      HttpResponse response = httpClient.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        return true;
      } else {
        return false;
      }

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      Log.i("FailedTOInsert", "failed");
      return false;
    } catch (ClientProtocolException e) {
      Log.i("FailedTOInsert", "failed");
      return false;
    } catch (IOException e) {
      Log.i("FailedTOInsert", "failed");
      return false;
    }
  }