protected Object execute(Request request, HttpUriRequest httpReq) throws Exception {
   for (Map.Entry<String, String> entry : request.entrySet()) {
     httpReq.setHeader(entry.getKey(), entry.getValue());
   }
   HttpResponse resp = executeRequestWithTimeout(httpReq);
   HttpEntity entity = resp.getEntity();
   int status = resp.getStatusLine().getStatusCode();
   if (entity == null) {
     if (status < 400) {
       return null;
     }
     throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
   }
   Header ctypeHeader = entity.getContentType();
   if (ctypeHeader == null) { // handle broken responses with no ctype
     if (status != 200) {
       // this may happen when login failed
       throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
     }
     return null; // cannot handle responses with no ctype
   }
   String ctype = ctypeHeader.getValue();
   String disp = null;
   Header[] hdisp = resp.getHeaders("Content-Disposition");
   if (hdisp != null && hdisp.length > 0) {
     disp = hdisp[0].getValue();
   }
   return request.handleResult(status, ctype, disp, entity.getContent());
 }
  /** Handle the httpResponse and return the SOAP XML String. */
  protected String handleResponse(final HttpResponse response, final HttpContext context)
      throws IOException {
    final HttpEntity entity = response.getEntity();
    if (null == entity.getContentType()
        || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
      throw new WinRMRuntimeIOException(
          "Error when sending request to "
              + getTargetURL()
              + "; Unexpected content-type: "
              + entity.getContentType());
    }

    final InputStream is = entity.getContent();
    final Writer writer = new StringWriter();
    final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
      int n;
      final char[] buffer = new char[1024];
      while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
      }
    } finally {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(is);
      EntityUtils.consume(response.getEntity());
    }

    return writer.toString();
  }
示例#3
0
  @Test
  public void testUnboundVariable() throws Exception {
    String uri = "avg_ages";

    String aggregationsMetadata =
        "{\"aggrs\": ["
            + "{"
            + "\"type\":\"mapReduce\""
            + ","
            + "\"uri\": \""
            + uri
            + "\","
            + "\"map\": \"function() { emit(this.name, this.age) }\""
            + ","
            + "\"reduce\":\"function(key, values) { return Array.avg(values) }\""
            + ","
            + "\"query\":{\"name\":{\"_$var\":\"name\"}}"
            + "}]}";

    createTmpCollection();
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri);

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_BAD_REQUEST, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());
  }
 HttpEntityBody(HttpEntity httpentity, String s) {
   entity = httpentity;
   if (s != null) {
     mediaType = MediaType.parse(s);
     return;
   }
   if (httpentity.getContentType() != null) {
     mediaType = MediaType.parse(httpentity.getContentType().getValue());
     return;
   } else {
     mediaType = DEFAULT_MEDIA_TYPE;
     return;
   }
 }
  private JSONObject prepareRequestAndExtractResponse(HttpUriRequest request) throws HTTPError {
    if (key != null) {
      String encoding = "";
      try {
        encoding = Base64.encodeBase64String((key + ":").getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
      }
      request.setHeader("Authorization", "Basic " + encoding + "=");
    }

    HttpResponse response;
    try {
      response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    String body = null;
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      try {
        body = EntityUtils.toString(entity);

      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 299
        && !ContentType.APPLICATION_JSON
            .getMimeType()
            .equals(
                (entity.getContentType() != null ? entity.getContentType().getValue() : null))) {
      throw new HTTPError(response, body);
    }

    JSONObject result;
    try {
      result = new JSONObject(body);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }

    return result;
  }
示例#6
0
  @SuppressWarnings("unchecked")
  private Sysprop fetchFxRatesJSON() {
    Map<String, Object> map = new HashMap<String, Object>();
    Sysprop s = new Sysprop();
    ObjectReader reader = ParaObjectUtils.getJsonReader(Map.class);

    try {
      CloseableHttpClient http = HttpClients.createDefault();
      HttpGet httpGet = new HttpGet(SERVICE_URL);
      HttpResponse res = http.execute(httpGet);
      HttpEntity entity = res.getEntity();

      if (entity != null && Utils.isJsonType(entity.getContentType().getValue())) {
        JsonNode jsonNode = reader.readTree(entity.getContent());
        if (jsonNode != null) {
          JsonNode rates = jsonNode.get("rates");
          if (rates != null) {
            map = reader.treeToValue(rates, Map.class);
            s.setId(FXRATES_KEY);
            s.setProperties(map);
            //						s.addProperty("fetched", Utils.formatDate("dd MM yyyy HH:mm", Locale.UK));
            dao.create(s);
          }
        }
        EntityUtils.consume(entity);
      }
      logger.debug("Fetched rates from OpenExchange for {}.", new Date().toString());
    } catch (Exception e) {
      logger.error("TimerTask failed: {}", e);
    }
    return s;
  }
示例#7
0
 private String sendBasic(HttpRequestBase request) throws HttpException {
   try {
     HttpResponse response = httpClient.execute(request);
     HttpEntity entity = response.getEntity();
     String body = "";
     if (entity != null) {
       body = EntityUtils.toString(entity, UTF_8);
       if (entity.getContentType() == null) {
         body = new String(body.getBytes(ISO_8859_1), UTF_8);
       }
     }
     int code = response.getStatusLine().getStatusCode();
     if (code < 200 || code >= 300) {
       throw new Exception(String.format(" code : '%s' , body : '%s'", code, body));
     }
     return body;
   } catch (Exception ex) {
     throw new HttpException(
         "Fail to send "
             + request.getMethod()
             + " request to url "
             + request.getURI()
             + ", "
             + ex.getMessage(),
         ex);
   } finally {
     request.releaseConnection();
   }
 }
示例#8
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;
  }
  /**
   * 将Entity的内容载入Page对象
   *
   * @date 2013-1-7 上午11:22:06
   * @param entity
   * @return
   * @throws Exception
   */
  private Page load(HttpEntity entity) throws Exception {
    Page page = new Page();

    // 设置返回内容的ContentType
    String contentType = null;
    Header type = entity.getContentType();
    if (type != null) contentType = type.getValue();
    page.setContentType(contentType);

    // 设置返回内容的字符编码
    String contentEncoding = null;
    Header encoding = entity.getContentEncoding();
    if (encoding != null) contentEncoding = encoding.getValue();
    page.setEncoding(contentEncoding);

    // 设置返回内容的字符集
    String contentCharset = EntityUtils.getContentCharSet(entity);
    page.setCharset(contentCharset);
    // 根据配置文件设置的字符集参数进行内容二进制话
    String charset = config.getCharset();
    String content = this.read(entity.getContent(), charset);
    page.setContent(content);
    //		if (charset == null || charset.trim().length() == 0)
    //			page.setContentData(content.getBytes());
    //		else
    //			page.setContentData(content.getBytes(charset));

    return page;
  }
示例#10
0
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
示例#11
0
  /**
   * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}.
   * The encoding is taken from the entity's Content-Encoding header.
   *
   * <p>This is typically used while parsing an HTTP POST.
   *
   * @param entity The entity to parse
   * @throws IOException If there was an exception getting the entity's data.
   */
  public static List<NameValuePair> parse(final HttpEntity entity) throws IOException {
    List<NameValuePair> result = Collections.emptyList();

    String contentType = null;
    String charset = null;

    Header h = entity.getContentType();
    if (h != null) {
      HeaderElement[] elems = h.getElements();
      if (elems.length > 0) {
        HeaderElement elem = elems[0];
        contentType = elem.getName();
        NameValuePair param = elem.getParameterByName("charset");
        if (param != null) {
          charset = param.getValue();
        }
      }
    }

    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
      final String content = EntityUtils.toString(entity, HTTP.ASCII);
      if (content != null && content.length() > 0) {
        result = new ArrayList<NameValuePair>();
        parse(result, new Scanner(content), charset);
      }
    }
    return result;
  }
  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;
  }
示例#13
0
 private Plain asPlain(org.apache.http.HttpResponse response) throws IOException {
   assertThat(response.getStatusLine().getStatusCode(), is(200));
   HttpEntity entity = response.getEntity();
   MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
   assertThat(mediaType.type(), is("application"));
   assertThat(mediaType.subtype(), is("json"));
   return Jsons.toObject(entity.getContent(), Plain.class);
 }
示例#14
0
  public static String getContentCharSet(final HttpEntity entity) throws ParseException {

    String charSet = null;

    if (entity.getContentType() != null) {
      HeaderElement values[] = entity.getContentType().getElements();

      if (values.length > 0) {
        NameValuePair param = values[0].getParameterByName("charset");

        if (param != null) {
          charSet = param.getValue();
        }
      }
    }
    return charSet;
  }
 public void testScrollEntity() throws IOException {
   String scroll = randomAsciiOfLength(30);
   HttpEntity entity = scrollEntity(scroll);
   assertEquals(ContentType.TEXT_PLAIN.toString(), entity.getContentType().getValue());
   assertEquals(
       scroll,
       Streams.copyToString(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)));
 }
示例#16
0
 public String getContentType() {
   HttpEntity responseEntity = resp.getEntity();
   if (responseEntity != null) {
     Header contentType = responseEntity.getContentType();
     if (contentType != null) return contentType.getValue();
   }
   return null;
 }
示例#17
0
  private void performAuthentication(DefaultHttpClient httpClient, AuthToken authToken)
      throws IOException, AuthenticationException {
    HttpResponse resp;
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, authToken.username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authToken.password));
    params.add(new BasicNameValuePair(PARAM_USER_TIME, "dummy"));
    final HttpEntity entity;
    try {
      entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
      // this should never happen.
      throw new IllegalStateException(e);
    }
    String uri =
        BASE_URL
            + "?"
            + URLEncodedUtils.format(
                Arrays.asList(new BasicNameValuePair(XML_ID, AUTH_XML_ID)), ENCODING);
    Log.i(TAG, "Authenticating to: " + uri);

    final HttpPost post = new HttpPost(uri);
    post.addHeader(entity.getContentType());
    post.setHeader("Accept", "*/*");
    post.setEntity(entity);
    resp = httpClient.execute(post);

    // check for bad status
    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
      throw new ParseException(
          "status after auth: "
              + resp.getStatusLine().getStatusCode()
              + " "
              + resp.getStatusLine().getReasonPhrase());
    }

    // check header redirect
    Header[] locations = resp.getHeaders(HEADER_LOCATION);
    if (locations.length != 1) {
      throw new ParseException(locations.length + " header locations received!");
    }

    String location = "https://" + DOMAIN + locations[0].getValue();
    Log.v(TAG, "location=" + location);

    UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(location);
    authToken.userId = sanitizer.getValue(PARAM_USER_ID);
    authToken.sessionId = sanitizer.getValue(PARAM_SESSION_ID);
    String redirectedXmlId = sanitizer.getValue(XML_ID);

    if (authToken.userId == null
        || authToken.userId.length() == 0
        || authToken.sessionId == null
        || authToken.sessionId.length() == 0
        || AUTH_XML_ID.equalsIgnoreCase(redirectedXmlId)) {
      checkAuthError(sanitizer);
    }
  }
 /**
  * Returns true if the entity's Content-Type header is <code>application/x-www-form-urlencoded
  * </code>.
  */
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 13:01:44.457 -0500",
     hash_original_method = "0BF3228161F0ACF43C700CE7A2BBAA2E",
     hash_generated_method = "8503EA47287EAF38F5D4E4E943CADED1")
 public static boolean isEncoded(final HttpEntity entity) {
   final Header contentType = entity.getContentType();
   return (contentType != null && contentType.getValue().equalsIgnoreCase(CONTENT_TYPE));
 }
示例#19
0
  private String getEtag(URI uri) throws IOException {
    Response resp = adminExecutor.execute(Request.Get(uri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json", json);

    assertNotNull("check not null _etag", json.get("_etag"));
    assertTrue("check _etag is object", json.get("_etag").isObject());

    assertNotNull("check not null _etag.$oid", json.get("_etag").asObject().get("$oid"));

    assertNotNull(
        "check _etag.$oid is string", json.get("_etag").asObject().get("$oid").isString());

    return json.get("_etag").asObject().get("$oid").asString();
  }
示例#20
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();
  }
示例#21
0
 /**
  * Returns true if the entity's Content-Type header is <code>application/x-www-form-urlencoded
  * </code>.
  */
 public static boolean isEncoded(final HttpEntity entity) {
   Header h = entity.getContentType();
   if (h != null) {
     HeaderElement[] elems = h.getElements();
     if (elems.length > 0) {
       String contentType = elems[0].getName();
       return contentType.equalsIgnoreCase(CONTENT_TYPE);
     } else {
       return false;
     }
   } else {
     return false;
   }
 }
示例#22
0
  public static Reader createReaderFromResponse(HttpResponse theResponse)
      throws IllegalStateException, IOException {
    HttpEntity entity = theResponse.getEntity();
    if (entity == null) {
      return new StringReader("");
    }
    Charset charset = null;
    if (entity.getContentType() != null
        && entity.getContentType().getElements() != null
        && entity.getContentType().getElements().length > 0) {
      ContentType ct = ContentType.get(entity);
      charset = ct.getCharset();
    }
    if (charset == null) {
      if (Constants.STATUS_HTTP_204_NO_CONTENT != theResponse.getStatusLine().getStatusCode()) {
        ourLog.warn("Response did not specify a charset.");
      }
      charset = Charset.forName("UTF-8");
    }

    Reader reader = new InputStreamReader(theResponse.getEntity().getContent(), charset);
    return reader;
  }
示例#23
0
  /** Verify that response matches supplied content type */
  public RequestExecutor assertContentType(String expected) {
    assertNotNull(this.toString(), response);
    if (entity == null) {
      fail(this + ": no entity in response, cannot check content type");
    }

    // Remove whatever follows semicolon in content-type
    String contentType = entity.getContentType().getValue();
    if (contentType != null) {
      contentType = contentType.split(";")[0].trim();
    }

    // And check for match
    assertEquals(this + ": expecting content type " + expected, expected, contentType);
    return this;
  }
示例#24
0
 /**
  * Extracts the string that denotes the boundary of the multipart response from Content-Type
  * header.
  *
  * @param httpEntity {@link HttpEntity} that holds a response.
  * @return Boundary word, or null if the Content-Type header does not define it.
  */
 public static String getBoundary(HttpEntity httpEntity) {
   Header contentTypeHeader = httpEntity.getContentType();
   if (contentTypeHeader == null) {
     return null;
   }
   StringTokenizer tokenizer = new StringTokenizer(contentTypeHeader.getValue(), ";");
   while (tokenizer.hasMoreTokens()) {
     String token = tokenizer.nextToken().trim();
     int boundaryIndex = token.indexOf(BOUNDARY_KEY);
     if (boundaryIndex != -1) {
       String boundaryString = token.substring(boundaryIndex + BOUNDARY_KEY.length());
       return boundaryString;
     }
   }
   return null;
 }
示例#25
0
  public static String getCharSet(HttpEntity entity) {
    if (entity == null) return null;

    Header header = entity.getContentType();
    if (header == null) return null;

    HeaderElement[] elements = header.getElements();
    if (elements.length > 0) {
      HeaderElement element = elements[0];
      NameValuePair param = element.getParameterByName("charset");
      if (param != null) {
        return param.getValue();
      }
    }

    return null;
  }
  public void testInitialSearchEntity() throws IOException {
    String query = "{\"match_all\":{}}";
    HttpEntity entity = initialSearchEntity(new BytesArray(query));
    assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
    assertEquals(
        "{\"query\":" + query + "}",
        Streams.copyToString(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)));

    // Invalid XContent fails
    RuntimeException e =
        expectThrows(
            RuntimeException.class,
            () -> initialSearchEntity(new BytesArray("{}, \"trailing\": {}")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected character (',' (code 44))"));
    e = expectThrows(RuntimeException.class, () -> initialSearchEntity(new BytesArray("{")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected end-of-input"));
  }
示例#27
0
  /*
   * posts an image to the users news feed
   * @param message to show
   * @param image as form data
   * @return the new image id if successful
   */
  public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request =
        new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accessTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
      // facebook requires multipart post structure
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.addTextBody("message", msg); // description

      if (placeId != null && !"".equals(placeId)) {
        builder.addTextBody(
            "place", placeId); // add link to FabLab site if property is set in preferences
      }

      // convert image to bytearray and append to multipart
      BufferedImage bimage =
          new BufferedImage(
              image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
      Graphics2D bGr = bimage.createGraphics();
      bGr.drawImage(image, 0, 0, null);
      bGr.dispose();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(bimage, "png", baos);
      builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

      // generate multipart byte stream and add to payload of post package
      HttpEntity multipart = builder.build();
      ByteArrayOutputStream multipartOutStream =
          new ByteArrayOutputStream((int) multipart.getContentLength());
      multipart.writeTo(multipartOutStream);
      request.addPayload(multipartOutStream.toByteArray());

      // set header of post package
      Header contentType = multipart.getContentType();
      request.addHeader(contentType.getName(), contentType.getValue());

      // send and response answer
      Response response = request.send();
      return response.getBody();
    } else {
      throw new RuntimeException(CONSTANTS.get(FACEBOOK_MESSAGE_IMG_NEEDED));
    }
  }
 /**
  * 执行请求,返回字节
  *
  * @param charset
  * @param httpUriRequest
  * @return
  */
 public byte[] execute_byte(HttpUriRequest httpUriRequest, Map<String, String> header) {
   byte[] data = null;
   HttpEntity entity = null;
   try {
     CloseableHttpResponse httpResponse = httpclient.execute(httpUriRequest);
     int statusCode = httpResponse.getStatusLine().getStatusCode();
     entity = httpResponse.getEntity();
     Header heade = entity.getContentType();
     if (heade != null) {
       log.info("statusCode : " + statusCode + " ContentType : " + heade.getValue());
       setContent_type(heade.getValue());
     } else {
       log.info("statusCode : " + statusCode + " ContentType : unknown .");
     }
     setStatusCode(statusCode);
     if (statusCode == 200) {
       data = EntityUtils.toByteArray(entity);
     } else if (statusCode == 302 || statusCode == 300 || statusCode == 301) {
       URL referer = httpUriRequest.getURI().toURL();
       httpUriRequest.abort();
       Header location = httpResponse.getFirstHeader("Location");
       String locationurl = location.getValue();
       if (!locationurl.startsWith("http")) {
         URL u = new URL(referer, locationurl);
         locationurl = u.toExternalForm();
       }
       data = GetImg(locationurl, header);
     } else {
       data = EntityUtils.toByteArray(entity);
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (httpUriRequest != null) {
       httpUriRequest.abort();
     }
     if (entity != null) {
       EntityUtils.consumeQuietly(entity);
     }
   }
   return data;
 }
 @Test
 public void testPrepareInputLengthDelimited() throws Exception {
   final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
   message.addHeader("Content-Length", "10");
   message.addHeader("Content-Type", "stuff");
   message.addHeader("Content-Encoding", "identity");
   final HttpEntity entity = conn.prepareInput(message);
   Assert.assertNotNull(entity);
   Assert.assertFalse(entity.isChunked());
   Assert.assertEquals(10, entity.getContentLength());
   final Header ct = entity.getContentType();
   Assert.assertNotNull(ct);
   Assert.assertEquals("stuff", ct.getValue());
   final Header ce = entity.getContentEncoding();
   Assert.assertNotNull(ce);
   Assert.assertEquals("identity", ce.getValue());
   final InputStream instream = entity.getContent();
   Assert.assertNotNull(instream);
   Assert.assertTrue((instream instanceof ContentLengthInputStream));
 }
  @Test
  public void testTooLargeEntityHasOriginalContentTypes() throws Exception {
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    StringEntity entity = new StringEntity("large entity content");
    response.setEntity(entity);

    impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response);

    impl.readResponse();
    boolean tooLarge = impl.isLimitReached();
    HttpResponse result = impl.getReconstructedResponse();
    HttpEntity reconstructedEntity = result.getEntity();
    Assert.assertEquals(entity.getContentEncoding(), reconstructedEntity.getContentEncoding());
    Assert.assertEquals(entity.getContentType(), reconstructedEntity.getContentType());

    String content = EntityUtils.toString(reconstructedEntity);

    Assert.assertTrue(tooLarge);
    Assert.assertEquals("large entity content", content);
  }