@Test
  public void testTransaction() throws Exception {
    String retVal = ourCtx.newXmlParser().encodeBundleToString(new Bundle());

    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
    when(ourHttpClient.execute(capt.capture())).thenReturn(ourHttpResponse);
    when(ourHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(ourHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_ATOM_XML + "; charset=UTF-8"));
    when(ourHttpResponse.getEntity().getContent())
        .thenReturn(new ReaderInputStream(new StringReader(retVal), Charset.forName("UTF-8")));

    Patient p1 = new Patient();
    p1.addIdentifier().setSystem("urn:system").setValue("value");

    IGenericClient client = ourCtx.newRestfulGenericClient("http://foo");
    client.transaction().withResources(Arrays.asList((IBaseResource) p1)).execute();

    HttpUriRequest value = capt.getValue();

    assertTrue("Expected request of type POST on long params list", value instanceof HttpPost);
    HttpPost post = (HttpPost) value;
    String body = IOUtils.toString(post.getEntity().getContent());
    IOUtils.closeQuietly(post.getEntity().getContent());
    ourLog.info(body);

    assertThat(
        body, Matchers.containsString("<type value=\"" + BundleTypeEnum.TRANSACTION.getCode()));
  }
  /**
   * This method sends a login POST request to ensure the authentication and then send the POST
   * request with the action needed
   */
  public String loginAndExecuteBuilder(
      String URI_LOGIN,
      String URI_ACTION,
      List<NameValuePair> nameValuePairsLogin,
      List<NameValuePair> nameValuePairsAction) {
    String result = new String();
    HttpPost httppost;

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response, response_action;
    HttpEntity entity, entity_action;

    try {
      httppost = new HttpPost(URI_LOGIN);
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsLogin));
      response = httpclient.execute(httppost);

      entity = response.getEntity();
      entity.getContent();
      entity.consumeContent();

      httppost = new HttpPost(URI_ACTION);

      // Url Encoding the POST parameters
      try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsAction));
      } catch (UnsupportedEncodingException e) {
        // writing error to Log
        Log.v(
            "NetworkTools",
            "Exception executing POST: " + URI_ACTION + " Exception: " + e.toString());
      }

      // Log.v("Interoperabilty","URI para buscar  " + buildHttpHostRequest(URI_ACTION,
      // convertStreamToString(httppost.getEntity().getContent())));
      HttpPost httppost_p =
          new HttpPost(
              buildHttpHostRequest(
                  URI_ACTION, convertStreamToString(httppost.getEntity().getContent())));

      response_action = httpclient.execute(httppost_p);
      entity_action = response_action.getEntity();

      if (entity_action != null) {
        result = new String();
        result = convertStreamToString(response_action);
        entity_action.consumeContent();
      }
    } catch (Exception e) {
      Log.v(
          "NetworkTools",
          "Exception in POST request: " + URI_ACTION + " Exception: " + e.toString());
      return "";
    }
    return result;
  }
예제 #3
0
  @Override
  public boolean matchesSafely(HttpRequestBase method) {
    boolean matches = true;
    if (type != null) {
      switch (type) {
        case GET:
          matches &= method instanceof HttpGet;
          break;
        case POST:
          matches &= method instanceof HttpPost;
          break;
        default:
          break;
      }
    }

    if (url != null) {
      try {
        matches &= url.equals(method.getURI().toString());
      } catch (Exception e) {
        Assert.fail();
      }
    }

    if (urlPattern != null) {
      try {
        matches &= urlPattern.matcher(method.getURI().toString()).matches();
      } catch (Exception e) {
        Assert.fail();
      }
    }

    if (method instanceof HttpPost) {
      HttpPost postMethod = (HttpPost) method;
      HttpEntity entity = postMethod.getEntity();
      if (entity instanceof StringEntity) {
        String content = "";
        try {
          content = IOUtils.toString(((StringEntity) entity).getContent());
        } catch (IOException e) {
          e.printStackTrace();
          return false;
        }
        if (postBody != null) {
          matches &= postBody.equals(content);
        }

        if (postBodyPattern != null) {
          matches &= postBodyPattern.matcher(content).matches();
        }
      }
    }
    return matches;
  }
예제 #4
0
파일: Mac.java 프로젝트: dyglcc/mmwd
  /*
   * makes an access token.
   */
  public String signRequest(HttpPost post) throws AuthException {
    URI uri = post.getURI();
    String path = uri.getRawPath();
    String query = uri.getRawQuery();
    HttpEntity entity = post.getEntity();

    byte[] secretKey = this.secretKey.getBytes();
    javax.crypto.Mac mac = null;
    try {
      mac = javax.crypto.Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException e) {
      throw new AuthException("No algorithm called HmacSHA1!", e);
    }

    SecretKeySpec keySpec = new SecretKeySpec(secretKey, "HmacSHA1");
    try {
      mac.init(keySpec);
      mac.update(path.getBytes());
    } catch (InvalidKeyException e) {
      throw new AuthException("You've passed an invalid secret key!", e);
    } catch (IllegalStateException e) {
      throw new AuthException(e);
    }

    if (query != null && query.length() != 0) {
      mac.update((byte) ('?'));
      mac.update(query.getBytes());
    }
    mac.update((byte) '\n');
    if (entity != null) {
      org.apache.http.Header ct = entity.getContentType();
      if (ct != null && ct.getValue() == "application/x-www-form-urlencoded") {
        ByteArrayOutputStream w = new ByteArrayOutputStream();
        try {
          entity.writeTo(w);
        } catch (IOException e) {
          throw new AuthException(e);
        }
        mac.update(w.toByteArray());
      }
    }

    byte[] digest = mac.doFinal();
    byte[] digestBase64 = EncodeUtils.urlsafeEncodeBytes(digest);

    StringBuffer b = new StringBuffer();
    b.append(this.accessKey);
    b.append(':');
    b.append(new String(digestBase64));

    return b.toString();
  }
예제 #5
0
  public String processPost(HttpPost post) {

    try {
      String msg = EntityUtils.toString(post.getEntity(), "UTF-8");
      Subject sub = Codec.fromJson(msg, Subject.class);
      subjectQueue.add(sub);
      String result = "添加成功";
      return result;
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      return "添加失败";
    }
  }
예제 #6
0
  @Test(timeOut = 5000)
  public void postUrlEncoded() throws ParseException, IOException {
    server.expect(
        Condition.when("POST").respond("{\"id\":\"ABCDEFG\"}", ContentType.APPLICATION_JSON));

    Card in = new Card("Hello", "world", "0989080");

    HttpPost req = (HttpPost) Post(baseUrl).bean(in).build();
    Assert.assertEquals(
        EntityUtils.toString(req.getEntity()), "name=Hello&desc=world&idList=0989080");

    Member out = Post(baseUrl + "/").bean(in).map(Member.class);
    Assert.assertEquals(out.id, "ABCDEFG");
  }
  private static void printDebugInfo(HttpUriRequest request, HttpResponse response) {
    String br = System.getProperty("line.separator");
    StringBuffer builder = new StringBuffer();
    builder.append("URL: ");
    builder.append(request.getURI().toString());
    builder.append(br);
    builder.append("Request Headers: ");
    builder.append(headersToString(request.getAllHeaders()));
    builder.append(br);
    builder.append("Request Body: ");
    if (request instanceof HttpPost) {
      HttpPost post = (HttpPost) request;
      String body = "This body can't be outputted.";
      try {
        body = ResponseUtil.fromHttpEntityToString(post.getEntity(), "UTF-8");
      } catch (ResponseBodyParseException e) {
        Log.d(TAG, "Parsing request is failed.", e);
      }
      builder.append(body);
    } else {
      builder.append("No body by Get request.");
    }
    builder.append(br);
    builder.append("HTTP Status Code: ");
    builder.append(response.getStatusLine().getStatusCode());
    builder.append(br);
    builder.append("Response Headers: ");
    builder.append(headersToString(response.getAllHeaders()));
    builder.append(br);
    Header contentType = response.getFirstHeader("Content-Type");
    if (contentType != null && "application/json".equals(contentType.getValue())) {
      builder.append("Response Body: ");
      String body = "This body can't be outputted.";
      try {
        body = ResponseUtil.fromHttpEntityToString(response.getEntity(), "UTF-8");
        response.setEntity(new StringEntity(body, "UTF-8"));
      } catch (ResponseBodyParseException e) {
        Log.d(TAG, "Parsing response is failed.", e);
      } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.getMessage());
      }
      builder.append(body);
      builder.append(br);
    } else {
      builder.append("Response Body is binary data.");
      builder.append(br);
    }

    Log.d(TAG, builder.toString());
  }
 /**
  * If passed httpMethod is of type HttpPost then obtain its entity. If the entity has an enclosing
  * File then delete it by invoking this method after the request has completed. The entity will
  * have an enclosing File only if it was too huge to fit into memory.
  *
  * @see #writeRequestBodyToOutputStream(ClientRequest)
  * @param httpMethod - the httpMethod to clean up.
  */
 protected void cleanUpAfterExecute(final HttpRequestBase httpMethod) {
   if (httpMethod != null && httpMethod instanceof HttpPost) {
     HttpPost postMethod = (HttpPost) httpMethod;
     HttpEntity entity = postMethod.getEntity();
     if (entity != null && entity instanceof FileExposingFileEntity) {
       File tempRequestFile = ((FileExposingFileEntity) entity).getFile();
       try {
         boolean isDeleted = tempRequestFile.delete();
         if (!isDeleted) {
           handleFileNotDeletedError(tempRequestFile, null);
         }
       } catch (Exception ex) {
         handleFileNotDeletedError(tempRequestFile, ex);
       }
     }
   }
 }
예제 #9
0
    @Override
    protected String doInBackground(String... voids) {
      try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("Content-Type", "application/json");
        JSONObject obj = new JSONObject();
        obj.put("prenom", person.getPrenom());
        obj.put("nom", person.getNom());
        obj.put("sexe", person.getSexe());
        obj.put("password", person.getPassword());
        obj.put("createdby", person.getcreatedBy());
        obj.put("email", person.getEmail());
        obj.put("telephone", person.getTelephone());
        StringEntity entity = new StringEntity(obj.toString());

        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

        BufferedReader rd =
            new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
          result.append(line);
        }

        System.out.println(result.toString());
        return result.toString();
      } catch (Exception e) {

      }
      return null;
    }
  /** @param myParmas a post parameters ('client_id, client_secret, url_callback, ...') */
  public String postUrl(ArrayList<BasicNameValuePair> myParmas, String url) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    try {
      if (myParmas != null) {
        post.setEntity(new UrlEncodedFormEntity(myParmas));
      }
      log.debug("post : " + post + "Entity = " + post.getEntity());

      try {
        HttpResponse response = client.execute(post);

        log.trace("post executed");
        log.debug("-HTTP Response  :" + response);

        HttpEntity entity = response.getEntity();
        log.trace("HttpEntity fetched");
        if (entity == null) throw new IOException("No entity");
        log.trace("HttpEntity not null :)");

        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String answer = readBuffer(br);
        log.info("- requeste response : " + answer);
        return answer;

      } catch (ClientProtocolException e) {
        log.error("Error during execution, ", e);
      } catch (IOException e) {
        log.error("Error during execution, ", e);
      }
    } catch (Exception e1) {
      log.debug(" Error on setEntity :", e1);
    }

    return null;
  }
  @Test
  public void shouldUseOnlyLastCoffeeStatusForUpdates() throws Exception {
    CoffeeStatus coffeeStatus1 = new CoffeeStatus();
    CoffeeStatus coffeeStatus2 = new CoffeeStatus();
    coffeeStatus2.cupsRemaining = 999;
    coffeeStatus2.carafePresent = true;
    coffeeStatus2.lastBrewed = 888;

    coffeeStatusProcessor.coffeeStatus(coffeeStatus1);
    coffeeStatusProcessor.coffeeStatus(coffeeStatus2);

    HeartbeatEvent heartbeatEvent = new HeartbeatEvent();
    coffeeStatusProcessor.heartbeatEvent(heartbeatEvent);

    ArgumentCaptor<HttpPost> httpPostArgumentCaptor = ArgumentCaptor.forClass(HttpPost.class);

    verify(mockHttpClient, times(1)).execute(httpPostArgumentCaptor.capture());

    HttpPost httpPost = httpPostArgumentCaptor.getValue();
    String content = IOUtils.toString(httpPost.getEntity().getContent());

    String carafePresentString =
        coffeeStatusProcessor.getCarafePresentName()
            + "="
            + Boolean.toString(coffeeStatus2.carafePresent);
    String cupsRemainingString =
        coffeeStatusProcessor.getCupsRemainingName()
            + "="
            + String.valueOf(coffeeStatus2.cupsRemaining);
    String lastBrewedString =
        coffeeStatusProcessor.getLastBrewedName() + "=" + String.valueOf(coffeeStatus2.lastBrewed);

    Assert.assertThat(content, containsString(carafePresentString));
    Assert.assertThat(content, containsString(cupsRemainingString));
    Assert.assertThat(content, containsString(lastBrewedString));
  }
예제 #12
0
    @Override
    protected String doInBackground(Void... voidstr) {
      JSONObject jsonObject = new JSONObject();

      try {
        jsonObject.accumulate("firstName", firstName);
        jsonObject.accumulate("lastName", lastName);
        jsonObject.accumulate("phoneNumber", phoneNumber);
        jsonObject.accumulate("address", addr);

        // Add a nested JSONObject (e.g. for header information)
        JSONObject header = new JSONObject();
        header.put("deviceType", "Android"); // Device type
        header.put("deviceVersion", "2.0"); // Device OS version
        header.put("language", "es-es"); // Language of the Android client
        jsonObject.put("header", header);
        // Output the JSON object we're sending to Logcat:

        URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);
        System.out.println("printing json object : " + jsonObject);
        String se;
        se = jsonObject.toString();
        System.out.println("printing se : " + se);

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString());
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length());
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you
        // would like to use gzip compression

        InputStream inp = httpPostRequest.getEntity().getContent();
        String req = convertStreamToString(inp);
        System.out.println("printing entities : " + req);

        System.out.println("printing http request message : message is :" + httpPostRequest);
        HttpResponse response = null;
        try {
          response = (HttpResponse) httpclient.execute(httpPostRequest);
        } catch (Exception ex) {
          System.out.println("printing error :" + ex);
        }
        InputStream is = response.getEntity().getContent();
        String res = convertStreamToString(is);
        System.out.println("printing Response is :" + res);
        System.out.println("printing response code : " + response.getStatusLine().getStatusCode());

        // Get hold of the response entity (-> the data)
        HttpEntity entity = response.getEntity();
        String serverresp = entity.toString();
        System.out.println(
            "printing server response, entity length : " + entity.getContentLength());
        System.out.println("printing server response : " + serverresp);

        if (entity != null) {
          // Read the content stream
          InputStream instream = entity.getContent();
          Header contentEncoding = response.getFirstHeader("Content-Encoding");
          if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
          }
          System.out.println("Debug point : 1.3");
          // convert content stream to a String
          String resultString = convertStreamToString(instream);
          instream.close();
          resultString =
              resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

          // Transform the String into a JSONObject
          JSONObject jsonObjRecv = new JSONObject(resultString);
          // Raw DEBUG output of our received JSON object:
          Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
          System.out.println("Debug point : 1.4");
          return jsonObjRecv;
        }
        // return serverresp;

        try {
          // Add your data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("q", se));
          httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          System.out.println("printing http params: " + httpPostRequest.getParams().toString());
          // Execute HTTP Post Request
          HttpResponse response = httpclient.execute(httpPostRequest);

        } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
        } catch (IOException e) {
          // TODO Auto-generated catch block
        }
      } catch (Exception e) {
        System.out.println("Debug point : 1.4(a)");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
      }
      return null;
    }