示例#1
1
    @Override
    protected String doInBackground(String... params) {

      byte[] result = null;
      String str = "";

      HttpClient client = new DefaultHttpClient();
      //            HttpGet request = new
      // HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"+mSettings.getString(APP_PREFERENCES_TOKENID,"tokenId"));
      HttpGet request = new HttpGet("https://backfinecar-renatdk.c9.io/api/Cars");

      HttpResponse response;

      try {
        response = client.execute(request);
        result = EntityUtils.toByteArray(response.getEntity());
        str = new String(result, "UTF-8");
        Log.d("Response of GET request", response.toString());
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return str;
    }
  public byte[] handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
    if (hr.getStatusLine().getStatusCode() == 200) {
      if (hr.getEntity().getContentEncoding() == null) {
        return EntityUtils.toByteArray(hr.getEntity());
      }

      if (hr.getEntity().getContentEncoding().getValue().contains("gzip")) {
        GZIPInputStream gis = null;
        try {
          gis = new GZIPInputStream(hr.getEntity().getContent());
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          byte[] b = new byte[1024];
          int n;
          while ((n = gis.read(b)) != -1) baos.write(b, 0, n);
          System.out.println("Gzipped");
          return baos.toByteArray();
        } catch (IOException e) {
          throw e;
        } finally {
          try {
            if (gis != null) gis.close();
          } catch (IOException ex) {
            throw ex;
          }
        }
      }
      return EntityUtils.toByteArray(hr.getEntity());
    }

    if (hr.getStatusLine().getStatusCode() == 302) {
      throw new IOException("302");
    }
    return null;
  }
示例#3
0
  public static String download(String urlStr) {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(urlStr);

    // add request header
    final String USER_AGENT =
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
    request.addHeader("User-Agent", USER_AGENT);
    HttpResponse response;
    try {
      response = client.execute(request);

      byte[] rawresponse = EntityUtils.toByteArray(response.getEntity());

      String encoding = HTML_Downloader.detectEncoding(new String(rawresponse));
      if (encoding != null) {
        return new String(rawresponse, encoding);
      } else {
        return new String(rawresponse, "utf8");
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
示例#4
0
  public static void main(String[] args) throws Exception {

    String url = "https://localhost/service/notifyFromMO9.e";
    NotifyToMo9 notify = new NotifyToMo9();

    Map<String, String> formEntity = new TreeMap<String, String>();
    Map<String, String> headerEntity = new TreeMap<String, String>();
    headerEntity.put(
        "User-Agent",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
    PayPartnerManager partnerManager = (PayPartnerManager) context.getBean("payPartnerManager");

    TradeBean trade = new TradeBean();
    trade.setInvoice("881d36e647c64b63a99ab6b654451b51");
    trade.setChannelId(Constants.CHANNEL_ID_MO9 + "");

    formEntity.put("invoice", trade.getInvoice());
    formEntity.put("channelId", trade.getChannelId());

    HttpPost post = new HttpPost(url);
    HttpClient httpClient = HttpUtil.getThreadSafeHttpClient();
    HttpResponse response = HttpUtil.doPost(httpClient, post, formEntity, "UTF-8");

    String content = null;
    if (response.getEntity() != null) {
      String charset =
          EntityUtils.getContentCharSet(response.getEntity()) == null
              ? "UTF-8"
              : EntityUtils.getContentCharSet(response.getEntity());
      content = new String(EntityUtils.toByteArray(response.getEntity()), charset);
    }
    System.out.println(content);
  }
示例#5
0
  /**
   * 画像取得するために、画像URLを渡して、バイト配列を取得する。 一応、画像じゃなくても取得は可能だと思われる。
   *
   * @param url
   * @return
   */
  public static byte[] getImage(String url) {
    byte[] result = new byte[0];

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(url);

    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(method);
      entity = response.getEntity();
      result = EntityUtils.toByteArray(entity);
    } catch (ClientProtocolException e) {
      method.abort();
      e.printStackTrace();
    } catch (IOException e) {
      method.abort();
      e.printStackTrace();
    } finally {
      try {
        if (entity != null) {
          entity.consumeContent();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.getConnectionManager().shutdown();

    return result;
  }
  public List<BpTreeNode> getTree(String id, String ontology, String apiKey) throws IOException {
    String url = BP_API_BASE + BP_ONTOLOGIES + ontology + "/" + BP_CLASSES + id + "/tree";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The tree was successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      List<BpTreeNode> nodes = new ArrayList<>();
      for (JsonNode n : bpResult) {
        nodes.add(mapper.convertValue(n, BpTreeNode.class));
      }
      return nodes;
    } else {
      throw new HTTPException(statusCode);
    }
  }
  public BpPagedResults<BpClass> findAllClassesInOntology(
      String ontology, int page, int pageSize, String apiKey) throws HTTPException, IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + "?include=prefLabel,hasChildren,created,synonym,definition"
            + "&page="
            + page
            + "&pagesize="
            + pageSize;

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The classes were successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.readValue(
          mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {});
    } else {
      throw new HTTPException(statusCode);
    }
  }
  public BpClass find(String id, String ontology, String apiKey) throws HTTPException, IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + id
            + "?include=prefLabel,hasChildren,created,synonym,definition";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // The class was successfully retrieved
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.convertValue(bpResult, BpClass.class);
    } else {
      throw new HTTPException(statusCode);
    }
  }
  public BpPagedResults<BpClass> findValueSetsByValueSetCollection(
      String vsCollection, int page, int pageSize, String apiKey) throws IOException {
    String url =
        BP_API_BASE
            + BP_SEARCH
            + "?also_search_provisional=true&valueset_roots_only=true&ontology_types=VALUE_SET_COLLECTION&ontologies="
            + vsCollection
            + "&page="
            + page
            + "&pagesize="
            + pageSize;

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // Success
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      return mapper.readValue(
          mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {});
    } else {
      throw new HTTPException(statusCode);
    }
  }
    private byte[] postRequest(String url, byte[] drmRequest) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url + "&signedRequest=" + new String(drmRequest));

      Log.d(TAG, "PostRequest:" + httpPost.getRequestLine());
      try {
        // Add data
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("User-Agent", "Widevine CDM v1.0");
        httpPost.setHeader("Content-Type", "application/json");

        // Execute HTTP Post Request
        HttpResponse response = httpClient.execute(httpPost);

        byte[] responseBody;
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == 200) {
          responseBody = EntityUtils.toByteArray(response.getEntity());
        } else {
          Log.d(TAG, "Server returned HTTP error code " + responseCode);
          return null;
        }
        return responseBody;
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }
  /**
   * Writes the specified TaskResult data to the channel output. Only the raw output data is written
   * and rest of the TaskResult fields are ignored
   *
   * @param ctx the ChannelHandlerContext
   * @param event the ChannelEvent
   * @throws Exception in case of any errors
   */
  private void writeCommandExecutionResponse(
      ChannelHandlerContext ctx, ChannelEvent event, HttpResponse response) throws Exception {
    // Don't write anything if the response is null
    if (response == null) {
      // write empty response
      event
          .getChannel()
          .write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT))
          .addListener(ChannelFutureListener.CLOSE);
      return;
    }
    org.jboss.netty.handler.codec.http.HttpResponse httpResponse =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.getStatusLine().getStatusCode()));
    // write headers
    for (Header header : response.getAllHeaders()) {
      if (!RoutingHttpChannelHandler.REMOVE_HEADERS.contains(header.getName())) {
        httpResponse.setHeader(header.getName(), header.getValue());
      }
    }

    // write entity
    HttpEntity responseEntity = response.getEntity();
    byte[] responseData = EntityUtils.toByteArray(responseEntity);
    httpResponse.setContent(ChannelBuffers.copiedBuffer(responseData));
    // write response
    event.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
  }
示例#12
0
  /* background */
  @Override
  protected String doInBackground(String... params) {
    byte[] result = null;
    String str = "";
    HttpClient client = new DefaultHttpClient();
    Log.d("url", BASE_URL + params[0]);
    HttpPost post = new HttpPost(BASE_URL + params[0]); // in this case, params[0] is URL
    try {
      // set up post data
      ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
      Iterator<String> it = mData.keySet().iterator();
      while (it.hasNext()) {
        String key = it.next();
        nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
      }

      post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
      HttpResponse response = client.execute(post);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
        result = EntityUtils.toByteArray(response.getEntity());
        str = new String(result, "UTF-8");
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      Log.d("unsupported encoding exception", e.toString());
    } catch (Exception e) {
      e.printStackTrace();
      Log.d("exception", e.toString());
    }
    return str;
  }
示例#13
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;
  }
示例#14
0
 /**
  * 下载APK文件,返回下载完成的目录
  *
  * @param path
  * @return
  */
 public static String downLoadApk(String path) {
   byte[] data = null;
   HttpGet httpGet = new HttpGet(path);
   File file = Environment.getExternalStorageDirectory();
   FileOutputStream outputStream = null;
   try {
     HttpResponse httpResponse = httpClient.execute(httpGet);
     if (httpResponse.getStatusLine().getStatusCode() == 200) {
       data = EntityUtils.toByteArray(httpResponse.getEntity());
       if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
         outputStream = new FileOutputStream(new File(file, Constants.JVE_APK_NAME));
         outputStream.write(data, 0, data.length);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (outputStream != null) {
       try {
         outputStream.close();
       } catch (Exception e2) {
         e2.printStackTrace();
       }
     }
   }
   return file.getAbsolutePath() + "/" + Constants.JVE_APK_NAME;
 }
  public List<BpClass> getParents(String id, String ontology, String apiKey) throws IOException {
    String url =
        BP_API_BASE
            + BP_ONTOLOGIES
            + ontology
            + "/"
            + BP_CLASSES
            + id
            + "/parents"
            + "?include=prefLabel,hasChildren,created,synonym,definition";

    HttpResponse response =
        HttpUtil.makeHttpRequest(
            Request.Get(url)
                .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey))
                .connectTimeout(connectTimeout)
                .socketTimeout(socketTimeout));

    int statusCode = response.getStatusLine().getStatusCode();
    // Success
    if (statusCode == 200) {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode bpResult =
          mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity())));
      List<BpClass> children = new ArrayList<>();
      for (JsonNode n : bpResult) {
        children.add(mapper.convertValue(n, BpClass.class));
      }
      return children;
    } else {
      throw new HTTPException(statusCode);
    }
  }
示例#16
0
文件: Network.java 项目: ndong211/bo
 /** 扩展卡不可用时直接从网络获取图片 */
 public byte[] httpGetUrlAsByte(String url) {
   try {
     int stateCode;
     HttpGet httpGet = new HttpGet(url);
     httpGet.setHeader(
         "Accept-Language",
         (Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry())
             .toLowerCase());
     HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
     stateCode = httpResponse.getStatusLine().getStatusCode();
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null && stateCode == 200) {
       if (httpResponse.getEntity().getContentEncoding() == null
           || httpResponse
                   .getEntity()
                   .getContentEncoding()
                   .getValue()
                   .toLowerCase()
                   .indexOf("gzip")
               < 0) {
         InputStream is = httpEntity.getContent();
         byte[] byt = readInStream(is);
         return byt;
       } else {
         InputStream is =
             new GZIPInputStream(new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity)));
         byte[] byt = readInStream(is);
         return byt;
       }
     }
   } catch (IOException e) {
   } catch (NullPointerException ex) {
   }
   return null;
 }
    @Override
    public void run() {

      HttpClient httpClient = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet(image_path);
      HttpResponse httpResponse = null;
      try {
        httpResponse = httpClient.execute(httpGet);
        /* Message m0 = new Message();

        m0.what=0;
        handler.sendMessage(m0);*/

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
          byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
          // 获取一个Message对象,设置what为1
          Message msg = Message.obtain();
          msg.obj = data;
          msg.what = IS_FINISH;
          // 发送这个消息到消息队列中
          handler.sendMessage(msg);
          // handler.sendMessageDelayed(msg, 5000);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
示例#18
0
  public static byte[] httpPost(String url, String entity) {
    if (url == null || url.length() == 0) {
      Log.e(TAG, "httpPost, url is null");
      return null;
    }

    HttpClient httpClient = getNewHttpClient();

    HttpPost httpPost = new HttpPost(url);

    try {
      httpPost.setEntity(new StringEntity(entity));
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      HttpResponse resp = httpClient.execute(httpPost);
      if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
        return null;
      }

      return EntityUtils.toByteArray(resp.getEntity());
    } catch (Exception e) {
      Log.e(TAG, "httpPost exception, e = " + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }
示例#19
0
 public byte[] bytes() {
   try {
     return EntityUtils.toByteArray(entity());
   } catch (IOException ex) {
     Logger.getLogger(Representation.class.getName()).log(Level.SEVERE, null, ex);
   }
   return null;
 }
示例#20
0
 // 从一个URL地址取得对象流;
 public static byte[] get(String url) throws Exception {
   HttpClient client = new DefaultHttpClient();
   HttpResponse response = client.execute(new HttpGet(url));
   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
     return EntityUtils.toByteArray(response.getEntity());
   }
   return null;
 }
 private Content handleEntity(final HttpEntity entity) throws IOException {
   Content content = null;
   if (entity != null) {
     content = new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity));
   } else {
     content = Content.NO_CONTENT;
   }
   return content;
 }
 /**
  * 执行请求,返回字节
  *
  * @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;
 }
示例#23
0
 /** Redirect to HTTP port. */
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   HttpClient client = HttpConnectionUtil.getClient(connectionTimeout);
   // setup POST
   HttpPost post = null;
   try {
     post = new HttpPost(postAcceptorURL);
     String path = req.getContextPath();
     if (path == null) {
       path = "";
     }
     log.debug("Path: {}", path);
     if (req.getPathInfo() != null) {
       path += req.getPathInfo();
     }
     log.debug("Path 2: {}", path);
     int reqContentLength = req.getContentLength();
     if (reqContentLength > 0) {
       log.debug("Request content length: {}", reqContentLength);
       IoBuffer reqBuffer = IoBuffer.allocate(reqContentLength);
       ServletUtils.copy(req, reqBuffer.asOutputStream());
       reqBuffer.flip();
       post.setEntity(new InputStreamEntity(reqBuffer.asInputStream(), reqContentLength));
       post.addHeader("Content-Type", REQUEST_TYPE);
       // get.setPath(path);
       post.addHeader("Tunnel-request", path);
       // execute the method
       HttpResponse response = client.execute(post);
       int code = response.getStatusLine().getStatusCode();
       log.debug("HTTP response code: {}", code);
       if (code == HttpStatus.SC_OK) {
         HttpEntity entity = response.getEntity();
         if (entity != null) {
           resp.setContentType(REQUEST_TYPE);
           // get the response as bytes
           byte[] bytes = EntityUtils.toByteArray(entity);
           IoBuffer resultBuffer = IoBuffer.wrap(bytes);
           resultBuffer.flip();
           ServletUtils.copy(resultBuffer.asInputStream(), resp.getOutputStream());
           resp.flushBuffer();
         }
       } else {
         resp.sendError(code);
       }
     } else {
       resp.sendError(HttpStatus.SC_BAD_REQUEST);
     }
   } catch (Exception ex) {
     log.error("", ex);
     if (post != null) {
       post.abort();
     }
   }
 }
 @Override
 public String handleResponse(HttpResponse response)
     throws ClientProtocolException, IOException {
   HttpEntity entity = response.getEntity();
   httpResult.setMessage(response.getStatusLine().getReasonPhrase());
   httpResult.setCode(response.getStatusLine().getStatusCode());
   StringBuilder out = new StringBuilder();
   byte[] data = EntityUtils.toByteArray(entity);
   out.append(new String(data, 0, data.length));
   return out.toString();
 }
示例#25
0
  @Test
  public void testHttpPostNoContentLength() throws Exception {
    this.server.registerHandler(
        "*",
        new HttpRequestHandler() {

          public void handle(
              final HttpRequest request, final HttpResponse response, final HttpContext context)
              throws HttpException, IOException {

            if (request instanceof HttpEntityEnclosingRequest) {
              final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
              final byte[] data = EntityUtils.toByteArray(incoming);
              final ByteArrayEntity outgoing = new ByteArrayEntity(data);
              response.setEntity(outgoing);
            } else {
              final StringEntity outgoing = new StringEntity("No content");
              response.setEntity(outgoing);
            }
          }
        });

    this.server.start();

    final DefaultBHttpClientConnection conn = client.createConnection();
    final HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
      if (!conn.isOpen()) {
        client.connect(host, conn);
      }

      final BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
      post.setEntity(null);

      this.client =
          new HttpClient(
              new ImmutableHttpProcessor(
                  new HttpRequestInterceptor[] {
                    new RequestTargetHost(),
                    new RequestConnControl(),
                    new RequestUserAgent(),
                    new RequestExpectContinue(true)
                  }));

      final HttpResponse response = this.client.execute(post, host, conn);
      Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
      final byte[] received = EntityUtils.toByteArray(response.getEntity());
      Assert.assertEquals(0, received.length);
    } finally {
      conn.close();
      this.server.shutdown();
    }
  }
  private FetchedDocument createFetchedDocument(HttpEntity entity) throws IOException {
    FetchedDocument fetchedDocument = new FetchedDocument();
    byte[] byteContent = EntityUtils.toByteArray(entity);
    ByteInfoHttpEntityWrapper byteInfoHttpEntityWrapper =
        new ByteInfoHttpEntityWrapper(entity, byteContent);

    fetchedDocument.setContentCharset(HttpUtils.getCharset(byteInfoHttpEntityWrapper));
    fetchedDocument.setContentType(HttpUtils.getContentType(byteInfoHttpEntityWrapper));
    fetchedDocument.setDocumentContent(byteContent);

    return fetchedDocument;
  }
示例#27
0
        public AjaxStatus handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {

          AjaxStatus ajaxResponse = new AjaxStatus();

          HttpEntity entity = response.getEntity();
          if (entity != null) ajaxResponse.setContent(EntityUtils.toByteArray(entity));

          ajaxResponse.setStatus(response.getStatusLine().getStatusCode());

          return ajaxResponse;
        }
  private byte[] getRadarImage() throws IOException {
    HttpGet request = new HttpGet(RADAR_URL);
    HttpResponse response = httpManager.execute(request);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
      return EntityUtils.toByteArray(response.getEntity());
    } else {
      String message = "invalid status code: " + statusCode;
      throw new IOException(message);
    }
  }
示例#29
0
 @Test
 public void testDefaultHandlerFavicon() throws Exception {
   try (CloseableHttpClient hc = HttpClients.createMinimal()) {
     try (CloseableHttpResponse res = hc.execute(new HttpGet(uri("/default/favicon.ico")))) {
       assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
       assertThat(
           res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(),
           startsWith("image/x-icon"));
       assertThat(EntityUtils.toByteArray(res.getEntity()).length, is(greaterThan(0)));
     }
   }
 }
  // Interface to AsyncHttpRequest
  @Override
  protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
      // malformed/ambiguous HTTP Header, ABORT!
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(
              status.getStatusCode(), "None, or more than one, Content-Type Header found!"),
          (String) null);
      return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
      if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
        foundAllowedContentType = true;
      }
    }
    if (!foundAllowedContentType) {
      // Content-Type not in allowed list, ABORT!
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
          (String) null);
      return;
    }
    try {
      HttpEntity entity = null;
      HttpEntity temp = response.getEntity();
      if (temp != null) {
        entity = new BufferedHttpEntity(temp);
      }
      responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
      sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
          responseBody);
    } else {
      sendSuccessMessage(status.getStatusCode(), responseBody);
    }
  }