示例#1
0
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

      AbstractHttpEntity entity;
      String uri = request.getRequestLine().getUri();
      int i = uri.indexOf(LIBRARY_URL);
      String sha1 = uri.substring(i + LIBRARY_URL.length());
      if (sha1.indexOf("?") != -1) {
        sha1 = sha1.substring(0, sha1.indexOf("?"));
      }
      System.out.println("sha1:" + sha1);

      URN urn = new URNImpl(com.limegroup.gnutella.URN.createSHA1Urn(sha1));
      if (libraryManager.getLibraryManagedList().contains(urn)) {
        FileDesc fileDesc = libraryManager.getLibraryManagedList().getFileDescsByURN(urn).get(0);
        entity = new NFileEntity(fileDesc.getFile(), "application/binary");
        entity.setContentType("application/binary");
        response.setHeader(
            "Content-disposition", "attachment; filename=\"" + fileDesc.getFileName() + "\";");
      } else {
        entity = new NStringEntity("File not found: " + sha1);
        entity.setContentType("text/plain");
      }
      response.setEntity(entity);
    }
 /**
  * Specifies the Content-Type header, as a string. The default implementation calls {@link
  * #setContentType(Header) setContentType(Header)}.
  *
  * @param ctString the new Content-Type header, or <code>null</code> to unset
  */
 public void setContentType(final String ctString) {
   Header h = null;
   if (ctString != null) {
     h = new BasicHeader(HTTP.CONTENT_TYPE, ctString);
   }
   setContentType(h);
 }
示例#3
0
  private void handleURLEncodedData(UrlEncodedFormEntity form) {
    AbstractHttpEntity entity = null;
    if (data != null) {
      try {
        entity = new StringEntity(data, "UTF-8");
      } catch (Exception ex) {
        // FIXME
        Log.e(LCAT, "Exception, implement recovery: ", ex);
      }
    } else {
      entity = form;
    }

    Header header = request.getFirstHeader("Content-Type");
    if (header == null) {
      entity.setContentType("application/x-www-form-urlencoded");
    } else {
      entity.setContentType(header.getValue());
    }

    HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
    e.setEntity(entity);
  }
示例#4
0
 protected void addEntity(HttpEntity entity, HttpRequestBase uriRequest) throws IOException {
   if (entity != null) {
     AbstractHttpEntity httpEntity = null;
     if (entity instanceof MultipartEntity) {
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       entity.writeTo(os);
       os.flush();
       httpEntity = new org.apache.http.entity.ByteArrayEntity(os.toByteArray());
       os.close();
     } else {
       httpEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength());
     }
     httpEntity.setContentType(entity.getContentType().toString());
     ((HttpEntityEnclosingRequestBase) uriRequest).setEntity(httpEntity);
   }
 }
示例#5
0
  /**
   * Serializes this object to an existing {@link HttpRequestBase} which can be sent as an HTTP
   * request. Specifically, sends the object's link, user-defined metadata and vclock as HTTP
   * headers and the value as the body. Used by {@link RiakClient} to create PUT requests.
   *
   * <p>if the this RiakObject's value is a stream, and no length is set, the stream is first
   * buffered into a byte array before being written
   */
  public void writeToHttpMethod(HttpRequestBase httpMethod) {
    // Serialize headers
    String basePath = getBasePathFromHttpMethod(httpMethod);
    writeLinks(httpMethod, basePath);
    for (String name : userMetaData.keySet()) {
      httpMethod.addHeader(Constants.HDR_USERMETA_REQ_PREFIX + name, userMetaData.get(name));
    }

    writeIndexes(httpMethod);

    if (vclock != null) {
      httpMethod.addHeader(Constants.HDR_VCLOCK, vclock);
    }

    // Serialize body
    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
      HttpEntityEnclosingRequestBase entityEnclosingMethod =
          (HttpEntityEnclosingRequestBase) httpMethod;
      AbstractHttpEntity entity = null;
      // Any value set using setValueAsStream() has precedent over value
      // set using setValue()
      if (valueStream != null) {
        if (valueStreamLength != null && valueStreamLength >= 0) {
          entity = new InputStreamEntity(valueStream, valueStreamLength);
        } else {
          // since apache http client 4.1 no longer supports buffering stream entities, but we can't
          // change API
          // behaviour, here we have to buffer the whole content
          entity = new ByteArrayEntity(ClientUtils.bufferStream(valueStream));
        }
      } else if (value != null) {
        entity = new ByteArrayEntity(value);
      } else {
        entity = new ByteArrayEntity(EMPTY);
      }
      entity.setContentType(contentType);
      entityEnclosingMethod.setEntity(entity);
    }
  }
示例#6
0
  @SuppressWarnings("unused")
  private void postRemoteRes(String url, final String data) {
    try {
      // 设置HttpClient超时参数
      HttpParams httpParameters = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);

      DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); // 创建http
      // client
      HttpPost httpPost = new HttpPost(url); // 创建http post
      AbstractHttpEntity entity = null;

      ContentProducer cp =
          new ContentProducer() {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
              // outstream.write(data.getBytes(HTTP.UTF_8));
              // outstream.flush();
              // outstream.close();
              Writer writer = new OutputStreamWriter(outstream, "UTF-8");
              writer.write(data);
              writer.flush();
              writer.close();
            }
          };
      entity = new EntityTemplate(cp);

      entity = new StringEntity(data, "utf-8");

      entity =
          new InputStreamEntity(
              new ByteArrayInputStream(data.getBytes(HTTP.UTF_8)),
              data.getBytes(HTTP.UTF_8).length);

      entity.setContentType("application/x-www-form-urlencoded");
      entity.setContentEncoding("utf-8");
      httpPost.setEntity(entity);

      // HttpResponse httpResponse = httpClient.execute(httpPost);//
      // 执行http 请求

      URL urls = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
      conn.setConnectTimeout(CONNECTION_TIMEOUT);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      OutputStream out = conn.getOutputStream();

      // 默认参数方式传递
      out.write(data.getBytes(HTTP.UTF_8));
      out.flush();
      out.close();
      InputStream is = conn.getInputStream();
      if (is != null) {

        // if (httpResponse != null
        // && httpResponse.getStatusLine().getStatusCode() ==
        // HttpStatus.SC_OK) {
        // InputStream is = httpResponse.getEntity().getContent();

        byte[] buffer = new byte[512];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readLength = 0;
        int offset = 0;
        mDataLen = 0;
        mDataRes = null;
        do {
          readLength = is.read(buffer);
          if (readLength > 0) {
            baos.write(buffer, 0, readLength);
            offset += readLength;
            mDataLen = offset;
          }
        } while (!mIsStopDl && readLength > 0);
        mDataRes = baos.toByteArray();
        baos.close();
        is.close();
      }

      // 下载完成
      Log.i(
          TAG,
          "downloadRemoteRes download completed. data length="
              + (mDataRes == null ? "null" : mDataRes.length)
              + " record length="
              + mDataLen
              + " url="
              + url);
      if (!mIsStopDl && (mDataRes == null || mDataRes.length == 0)) {
        Log.e(TAG, "data = null");
        if (mDlListener != null) mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_RESULT_NULL);
        return;
      }
      if (!mIsStopDl && mDlListener != null) {
        Log.d(TAG, "downloadRemoteRes ---- callback in.");
        mDlListener.onDlCompleted(mTaskTag, mDataRes, mDataLen);
        Log.d(TAG, "downloadRemoteRes ---- callback out.");
      }
    } catch (ConnectTimeoutException e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_TIME_OUT);
      }
    } catch (SocketTimeoutException e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_TIME_OUT);
      }
    } catch (Exception e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_OTHER);
      }
    }
  }