コード例 #1
0
ファイル: DavMethod.java プロジェクト: TaNhoSy/zimbra-mirror
 public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl)
     throws IOException, DavException {
   if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) {
     PostMethod method =
         new PostMethod(targetUrl) {
           @Override
           public String getName() {
             return getMethodName();
           }
         };
     RequestEntity reqEntry;
     if (ctxt.hasRequestMessage()) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       XMLWriter writer = new XMLWriter(baos);
       writer.write(ctxt.getRequestMessage());
       reqEntry = new ByteArrayRequestEntity(baos.toByteArray());
     } else { // this could be a huge upload
       reqEntry =
           new InputStreamRequestEntity(
               ctxt.getUpload().getInputStream(), ctxt.getUpload().getSize());
     }
     method.setRequestEntity(reqEntry);
     return method;
   }
   return new GetMethod(targetUrl) {
     @Override
     public String getName() {
       return getMethodName();
     }
   };
 }
コード例 #2
0
ファイル: HttpClient.java プロジェクト: Araell/prototype
  /** 支持multipart方式上传图片 */
  public Response multPartURL(String url, PostParameter[] params, ImageItem item, String token)
      throws WeiboException {
    PostMethod postMethod = new PostMethod(url);
    try {
      Part[] parts = null;
      if (params == null) {
        parts = new Part[1];
      } else {
        parts = new Part[params.length + 1];
      }
      if (params != null) {
        int i = 0;
        for (PostParameter entry : params) {
          parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
        }
        parts[parts.length - 1] =
            new ByteArrayPart(item.getContent(), item.getName(), item.getContentType());
      }
      postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

      return httpRequest(postMethod, token);

    } catch (Exception ex) {
      throw new WeiboException(ex.getMessage(), ex, -1);
    }
  }
コード例 #3
0
  private Entry addEntry(String endpointAddress) throws Exception {
    Entry e = createBookEntry(256, "AtomBook");
    StringWriter w = new StringWriter();
    e.writeTo(w);

    PostMethod post = new PostMethod(endpointAddress);
    post.setRequestEntity(new StringRequestEntity(w.toString(), "application/atom+xml", null));
    HttpClient httpclient = new HttpClient();

    String location = null;
    try {
      int result = httpclient.executeMethod(post);
      assertEquals(201, result);
      location = post.getResponseHeader("Location").getValue();
      InputStream ins = post.getResponseBodyAsStream();
      Document<Entry> entryDoc = abdera.getParser().parse(copyIn(ins));
      assertEquals(entryDoc.getRoot().toString(), e.toString());
    } finally {
      post.releaseConnection();
    }

    Entry entry = getEntry(location, null);
    assertEquals(location, entry.getBaseUri().toString());
    assertEquals("AtomBook", entry.getTitle());
    return entry;
  }
コード例 #4
0
ファイル: HttpUtil.java プロジェクト: zhouwei2008/casher
 /*     */ public static byte[] post(String url, RequestEntity requestEntity)
     /*     */ throws Exception
       /*     */ {
   /*  96 */ PostMethod method = new PostMethod(url);
   /*  97 */ method.addRequestHeader("Connection", "Keep-Alive");
   /*  98 */ method.getParams().setCookiePolicy("ignoreCookies");
   /*  99 */ method
       .getParams()
       .setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
   /* 100 */ method.setRequestEntity(requestEntity);
   /* 101 */ method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   /*     */ try
   /*     */ {
     /* 104 */ int statusCode = client.executeMethod(method);
     /* 105 */ if (statusCode != 200) {
       /* 106 */ return null;
       /*     */ }
     /* 108 */ return method.getResponseBody();
     /*     */ }
   /*     */ catch (SocketTimeoutException e) {
     /* 111 */ return null;
     /*     */ } catch (Exception e) {
     /* 113 */ return null;
     /*     */ } finally {
     /* 115 */ method.releaseConnection();
     /*     */ }
   /*     */ }
コード例 #5
0
ファイル: DataService.java プロジェクト: luinnx/box_android
  /**
   * 单次上传图片or文件
   *
   * @param path
   * @param name
   * @param filePath
   * @return
   * @throws Exception
   */
  public static String sendDataByHttpClientPost(String path, String name, String filePath)
      throws Exception {

    /*
     * List<Part> partList = new ArrayList<Part>(); partList.add(new
     * StringPart("user", name));
     *
     * for (int i = 0; i < 4; i++) { partList.add(new FilePart(name,
     * FilePart())); }
     */

    // 实例化上传数据的数组
    Part[] parts = {new StringPart("user", name), new FilePart("file", new File(filePath))};

    PostMethod filePost = new PostMethod(path);

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    org.apache.commons.httpclient.HttpClient client =
        new org.apache.commons.httpclient.HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    Log.e("Other", "返回结果:" + status);
    if (status == 200) {

      System.out.println(filePost.getResponseCharSet());
      String result = new String(filePost.getResponseBodyAsString());

      System.out.println("--" + result);
      return result;
    } else {
      throw new IllegalStateException("服务器状态异常");
    }
  }
コード例 #6
0
  public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception {
    String upload_url = this.fileUpload();

    PostMethod filePost = null;
    try {
      filePost = new PostMethod(upload_url);

      Part[] parts = {new FilePart("file", f)};

      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        ObjectMapper mapper = new ObjectMapper();
        DCObject json_response =
            DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class));
        return this.mediaCreate(json_response.pull("url"), assets_names, meta);
      } else {
        throw new DCException("Upload failed.");
      }
    } catch (Exception e) {
      throw new DCException("Upload failed: " + e.getMessage());
    } finally {
      if (filePost != null) {
        filePost.releaseConnection();
      }
    }
  }
コード例 #7
0
ファイル: ProxyServlet.java プロジェクト: alesj/hawtio
 /**
  * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the
  * given {@link HttpServletRequest}
  *
  * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a
  *     multipart POST request
  * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data
  *     to be sent via the {@link PostMethod}
  */
 @SuppressWarnings("unchecked")
 private void handleMultipartPost(
     PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
     throws ServletException {
   // Create a factory for disk-based file items
   DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
   // Set factory constraints
   diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
   diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
   // Create a new file upload handler
   ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
   // Parse the request
   try {
     // Get the multipart items as a list
     List<FileItem> listFileItems =
         (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
     // Create a list to hold all of the parts
     List<Part> listParts = new ArrayList<Part>();
     // Iterate the multipart items list
     for (FileItem fileItemCurrent : listFileItems) {
       // If the current item is a form field, then create a string part
       if (fileItemCurrent.isFormField()) {
         StringPart stringPart =
             new StringPart(
                 fileItemCurrent.getFieldName(), // The field name
                 fileItemCurrent.getString() // The field value
                 );
         // Add the part to the list
         listParts.add(stringPart);
       } else {
         // The item is a file upload, so we create a FilePart
         FilePart filePart =
             new FilePart(
                 fileItemCurrent.getFieldName(), // The field name
                 new ByteArrayPartSource(
                     fileItemCurrent.getName(), // The uploaded file name
                     fileItemCurrent.get() // The uploaded file contents
                     ));
         // Add the part to the list
         listParts.add(filePart);
       }
     }
     MultipartRequestEntity multipartRequestEntity =
         new MultipartRequestEntity(
             listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
     postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
     // The current content-type header (received from the client) IS of
     // type "multipart/form-data", but the content-type header also
     // contains the chunk boundary string of the chunks. Currently, this
     // header is using the boundary of the client request, since we
     // blindly copied all headers from the client request to the proxy
     // request. However, we are creating a new request with a new chunk
     // boundary string, so it is necessary that we re-set the
     // content-type string to reflect the new chunk boundary string
     postMethodProxyRequest.setRequestHeader(
         STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
   } catch (FileUploadException fileUploadException) {
     throw new ServletException(fileUploadException);
   }
 }
コード例 #8
0
 private HttpMethod createMultiPostMethod(String url, HttpData httpData) {
   PostMethod method = new InnerPostMethod(url);
   if (httpData != null) {
     List<Part> list = new ArrayList<Part>(httpData.getPatameterCount());
     Set<Map.Entry<String, String>> set = httpData.getParameterMap().entrySet();
     for (Map.Entry<String, String> e : set) {
       list.add(new StringPart(e.getKey(), e.getValue(), "utf-8"));
     }
     Set<Entry<String, List<String>>> bset = httpData.getBatchParameterMap().entrySet();
     for (Entry<String, List<String>> e : bset) {
       for (String s : e.getValue()) {
         list.add(new StringPart(e.getKey(), s, "utf-8"));
       }
     }
     try {
       for (HttpFile httpFile : httpData.getHttpFiles()) {
         list.add(new FilePart(httpFile.getName(), httpFile.getFile()));
       }
     } catch (FileNotFoundException e1) {
       throw new RuntimeException(e1);
     }
     method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
     MultipartRequestEntity mre =
         new MultipartRequestEntity(list.toArray(new Part[list.size()]), method.getParams());
     method.setRequestEntity(mre);
   }
   return method;
 }
コード例 #9
0
 public static String executePost(final String host, final String path, final List<Part> parts)
     throws Exception {
   final HttpClient client = new HttpClient();
   client.getParams().setParameter("http.protocol.single-cookie-header", true);
   client
       .getParams()
       .setParameter(
           "http.useragent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
   final HttpState httpState = new HttpState();
   final HostConfiguration hostConfiguration = new HostConfiguration();
   // add the proxy
   HttpProxy.addProxy(hostConfiguration);
   hostConfiguration.setHost(host);
   final MultipartRequestEntity entity =
       new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new HttpMethodParams());
   final PostMethod post = new PostMethod(getHostUrlPrefix(host) + path);
   post.setRequestEntity(entity);
   try {
     final int status = client.executeMethod(hostConfiguration, post, httpState);
     if (status != 200) {
       throw new Exception(
           "Post command to " + host + " failed, the server returned status: " + status);
     }
     return post.getResponseBodyAsString();
   } finally {
     post.releaseConnection();
   }
 }
コード例 #10
0
ファイル: HttpClient.java プロジェクト: sponte/selenium-grid
  private PostMethod convertHttpServletRequestToPostMethod(String url, HttpServletRequest request) {
    PostMethod postMethod = new PostMethod(url);

    for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
      String headerName = (String) headers.nextElement();
      String headerValue = (String) request.getHeader(headerName);
      postMethod.addRequestHeader(headerName, headerValue);
    }

    postMethod.removeRequestHeader("Host");
    postMethod.addRequestHeader("Host", request.getRequestURL().toString());

    for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ) {
      String paramName = (String) names.nextElement();
      String paramValue = (String) request.getParameter(paramName);
      postMethod.addParameter(paramName, paramValue);
    }

    StringBuilder requestBody = new StringBuilder();
    try {
      BufferedReader reader = request.getReader();
      String line;
      while (null != (line = reader.readLine())) {
        requestBody.append(line);
      }
      reader.close();
    } catch (IOException e) {
      requestBody.append("");
    }

    postMethod.setRequestEntity(new StringRequestEntity(requestBody.toString()));

    return postMethod;
  }
コード例 #11
0
ファイル: HttpUtil.java プロジェクト: guogongjun/myshop
  public static byte[] post(String url, RequestEntity requestEntity) throws Exception {

    PostMethod method = new PostMethod(url);
    method.addRequestHeader("Connection", "Keep-Alive");
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    method.setRequestEntity(requestEntity);
    method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("httpCode=" + statusCode);
        return method.getResponseBody();
      }
      return method.getResponseBody();

    } catch (SocketTimeoutException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      method.releaseConnection();
    }
  }
コード例 #12
0
ファイル: SimpleHttpClient.java プロジェクト: chenjw/spider
  @Override
  public Result multPartPost(
      HttpUrl url,
      String encoding,
      String cookie,
      Map<String, String> headers,
      String fileParamName,
      String fileName,
      byte[] fileBytes) {
    String realUrl = url.getRenderedUrl();
    PostMethod method = new PostMethod(realUrl);
    List<Part> partList = new ArrayList<Part>();

    if (url.getQueryParam() != null) {
      for (Entry<String, String> entry : url.getQueryParam().entrySet()) {
        partList.add(new StringPart(entry.getKey(), entry.getValue()));
      }
    }
    if (fileBytes != null) {
      partList.add(
          new FilePart(
              fileParamName,
              new ByteArrayPartSource(fileName, fileBytes),
              getContentType(fileName, fileBytes),
              "UTF-8"));
    }
    method.setRequestEntity(
        new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams()));
    Result result = excuteMethod(method, cookie, headers);
    result.setResultEncoding(encoding);
    return result;
  }
コード例 #13
0
 private void doPost(
     String realm,
     String host,
     String user,
     String pass,
     String url,
     boolean handshake,
     boolean preemtive,
     int result)
     throws Exception {
   HttpClient client = new HttpClient();
   client.getParams().setAuthenticationPreemptive(preemtive);
   client
       .getState()
       .setCredentials(
           new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass));
   PostMethod post = new PostMethod(url);
   post.setDoAuthentication(handshake);
   StringRequestEntity requestEntity = new StringRequestEntity(soapRequest, "text/xml", "UTF-8");
   post.setRequestEntity(requestEntity);
   try {
     int status = client.executeMethod(post);
     assertEquals(result, status);
     assertNotNull(post.getResponseBodyAsString());
   } finally {
     post.releaseConnection();
   }
 }
コード例 #14
0
 @Override
 public void run() {
   byte[] buffer = new byte[4096];
   while (!this.stats.isComplete()) {
     HttpMethod httpmethod;
     if (this.content == null) {
       GetMethod httpget = new GetMethod(target.toASCIIString());
       httpmethod = httpget;
     } else {
       PostMethod httppost = new PostMethod(target.toASCIIString());
       httppost.setRequestEntity(new ByteArrayRequestEntity(content));
       httpmethod = httppost;
     }
     long contentLen = 0;
     try {
       httpclient.executeMethod(httpmethod);
       InputStream instream = httpmethod.getResponseBodyAsStream();
       if (instream != null) {
         int l = 0;
         while ((l = instream.read(buffer)) != -1) {
           contentLen += l;
         }
       }
       this.stats.success(contentLen);
     } catch (IOException ex) {
       this.stats.failure(contentLen);
     } finally {
       httpmethod.releaseConnection();
     }
   }
 }
コード例 #15
0
ファイル: DataService.java プロジェクト: luinnx/box_android
  /**
   * 批量上传图片
   *
   * @param path 服务器地址
   * @param name 用户名
   * @param filePath sd卡图片路径
   * @param onSuccessListner
   * @return
   * @throws Exception
   */
  public static String sendDataByHttpClientPost(
      String path, List<File> files, List<Part> mparameters, OnSuccessListner listner)
      throws Exception {

    for (int i = 0; i < files.size(); i++) {
      mparameters.add(new FilePart("file", files.get(i)));
    }
    Part[] parts = mparameters.toArray(new Part[0]);

    PostMethod filePost = new PostMethod(path);
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    if (status == 200) {
      Log.e("DataService", "" + filePost.getResponseCharSet());
      String result = new String(filePost.getResponseBodyAsString());
      Log.e("DataService", "--" + result);
      // JSONArray array = (JSONArray) JSON.parse(result);
      Log.e("JSONArray", "--" + result);
      listner.onSuccess(result);
      return result;
    } else {
      listner.onFailed();
      return null;
    }
  }
コード例 #16
0
  /**
   * 发上服务器的文件
   *
   * @param file
   * @return
   */
  private String sendHttpRequest(File file) {
    String string = null;
    PostMethod filePost = new PostMethod(targetURL);
    try {
      Part[] parts = {
        new FilePart("userFile.file", targetFile), new StringPart(paramType, param, "utf-8")
      };
      HttpMethodParams params = filePost.getParams();
      params.setContentCharset("utf-8");
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(50000);

      Log.v("filePost", filePost.toString());
      Log.v("param", param);
      Log.v("paramType", paramType);
      int status = httpClient.executeMethod(filePost);
      // TODO
      Log.v("status--->", status + "");

      InputStream in = filePost.getResponseBodyAsStream();
      byte[] readStream = readStream(in);
      string = new String(readStream);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }
    return string;
  }
コード例 #17
0
ファイル: TestMultipartPost.java プロジェクト: cschneider/ecf
  /** Test that the body consisting of a file part can be posted. */
  public void testPostFilePart() throws Exception {

    this.server.setHttpService(new EchoService());

    PostMethod method = new PostMethod();
    byte[] content = "Hello".getBytes();
    MultipartRequestEntity entity =
        new MultipartRequestEntity(
            new Part[] {
              new FilePart(
                  "param1",
                  new ByteArrayPartSource("filename.txt", content),
                  "text/plain",
                  "ISO-8859-1")
            },
            method.getParams());
    method.setRequestEntity(entity);

    client.executeMethod(method);

    assertEquals(200, method.getStatusCode());
    String body = method.getResponseBodyAsString();
    assertTrue(
        body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"")
            >= 0);
    assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0);
    assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
    assertTrue(body.indexOf("Hello") >= 0);
  }
コード例 #18
0
  private static String login() throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod loginMethod = new PostMethod("http://*****:*****@gmail.com");
    loginRequest.setPassword("testpass");

    JAXBContext context = JAXBContext.newInstance("com.fb.platform.auth._1_0");
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(loginRequest, sw);

    StringRequestEntity requestEntity = new StringRequestEntity(sw.toString());
    loginMethod.setRequestEntity(requestEntity);

    int statusCode = httpClient.executeMethod(loginMethod);
    if (statusCode != HttpStatus.SC_OK) {
      System.out.println("unable to execute the login method : " + statusCode);
      return null;
    }
    String loginResponseStr = loginMethod.getResponseBodyAsString();
    System.out.println("Got the login Response : \n" + loginResponseStr);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    LoginResponse loginResponse =
        (LoginResponse)
            unmarshaller.unmarshal(new StreamSource(new StringReader(loginResponseStr)));

    return loginResponse.getSessionToken();
  }
コード例 #19
0
 public String POST(String uri, String content) throws IOException {
   PostMethod method = new PostMethod(url + uri);
   method.setRequestHeader("Accept", MESSAGE_FORMAT);
   RequestEntity body = new StringRequestEntity(content, MESSAGE_FORMAT, "UTF-8");
   method.setRequestEntity(body);
   client.executeMethod(method);
   return method.getResponseBodyAsString();
 }
コード例 #20
0
ファイル: Proxilet.java プロジェクト: eskatos/proxilet
  /**
   * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as
   * was sent in the given {@link HttpServletRequest}.
   *
   * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard
   *     POST request
   * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent
   *     via the {@link PostMethod}
   */
  private void handleContentPost(
      PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
      throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (; ; ) {
      String line = reader.readLine();
      if (line == null) {
        break;
      }
      content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this
    // servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module
    // 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
      String clientHost = httpServletRequest.getLocalName();
      if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
        clientHost = "localhost";
      }

      int clientPort = httpServletRequest.getLocalPort();
      String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
      String serverUrl =
          targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

      // Replace more completely if destination server is https :
      if (targetSsl) {
        clientUrl = "http://" + clientUrl;
        serverUrl = "https://" + serverUrl;
      }
      postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace(
        "POST Content Type: {} Encoding: {} Content: {}",
        new Object[] {contentType, encoding, postContent});
    StringRequestEntity entity;
    try {
      entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
  }
コード例 #21
0
ファイル: HttpClient.java プロジェクト: ahmatjan/workspace
  public Response multPartURL(
      String url, PostParameter[] params, ImageItem item, boolean authenticated)
      throws WeiboException {
    PostMethod post = new PostMethod(url);
    try {
      org.apache.commons.httpclient.HttpClient client = getHttpClient();
      long t = System.currentTimeMillis();
      Part[] parts = null;
      if (params == null) {
        parts = new Part[1];
      } else {
        parts = new Part[params.length + 1];
      }
      if (params != null) {
        int i = 0;
        for (PostParameter entry : params) {
          parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
        }
        parts[parts.length - 1] =
            new ByteArrayPart(item.getContent(), item.getName(), item.getContentType());
      }
      post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
      List<Header> headers = new ArrayList<Header>();

      if (authenticated) {
        if (oauth == null) {}
        String authorization = null;
        if (null != oauth) {
          // use OAuth
          authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken);
        } else {
          throw new IllegalStateException(
              "Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
        }
        headers.add(new Header("Authorization", authorization));
        log("Authorization: " + authorization);
      }
      client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
      client.executeMethod(post);

      Response response = new Response();
      response.setResponseAsString(post.getResponseBodyAsString());
      response.setStatusCode(post.getStatusCode());

      log(
          "multPartURL URL:"
              + url
              + ", result:"
              + response
              + ", time:"
              + (System.currentTimeMillis() - t));
      return response;
    } catch (Exception ex) {
      throw new WeiboException(ex.getMessage(), ex, -1);
    } finally {
      post.releaseConnection();
    }
  }
コード例 #22
0
 public void testHttpPost() throws URISyntaxException, HttpException, IOException {
   URI uri = new URI(HTTP_LOCALHOST_60198);
   PostMethod postMethod = new PostMethod(uri.toString());
   postMethod.setRequestEntity(new StringRequestEntity(TEST_MESSAGE));
   HttpConnection cnn = new HttpConnection(uri.getHost(), uri.getPort());
   cnn.open();
   postMethod.execute(new HttpState(), cnn);
   System.out.println("PostResponse: " + postMethod.getResponseBodyAsString());
 }
コード例 #23
0
ファイル: TestClient.java プロジェクト: xiaomozhang/ESBApp
  public static void main(String[] args) {
    // (1)构造HttpClient的实例
    HttpClient httpClient = new HttpClient();

    // (2)创建POST方法的实例
    PostMethod postMethod =
        new PostMethod("http://10.3.75.203:9080/ESB/appleServie?serviceCode=authentication");
    //		 GetMethod getMethod = new GetMethod("http://*****:*****@apple.com\",\"password\": \"Apple1234\", \"shipTo\":\"863348\",\"langCode\":\"en\",\"timeZone\":\"420\"}";
    postMethod.setRequestHeader("http.default-headers", authenticateText);
    // 使用系统提供的默认的恢复策略
    postMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
      postMethod.setRequestEntity(
          new StringRequestEntity(authenticateText, "text/xml; charset=UTF-8", "UTF-8"));
      // (4)执行postMethod
      int statusCode = httpClient.executeMethod(postMethod);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + postMethod.getStatusLine());
      }

      // (5)读取response头信息
      //			Header headerResponse = postMethod
      //					.getResponseHeader("response_key");
      //			String headerStr = headerResponse.getValue();
      // (6)读取内容
      byte[] responseBody = postMethod.getResponseBody();
      // (7) 处理内容
      //			System.out.println(headerStr);
      System.out.println("返回的内容信息:" + new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 释放连接
      postMethod.releaseConnection();
    }
  }
コード例 #24
0
 private void makePostRequest(final String url, final String content) throws Exception {
   final PostMethod method =
       (PostMethod) getMethodBuilder().setReferer(fileURL).setAction(url).toPostMethod();
   method.setRequestEntity(new StringRequestEntity(content, null, null));
   if (!makeRedirectedRequest(method)) {
     checkProblems();
     throw new ServiceConnectionProblemException();
   }
   checkProblems();
 }
  /*
   * Tests the <tt>havingRawBody</tt> method
   */
  @Test
  public void havingRawBody() throws IOException {
    onRequest().havingRawBodyEqualTo(BINARY_BODY).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    final int status = client.executeMethod(method);
    assertThat(status, is(201));
  }
コード例 #26
0
 // sends packet to server as a http post method
 private boolean sendPacketToServer(byte[] packet) {
   try {
     postMethod.removeRequestHeader("content-length");
     RequestEntity request = new ByteArrayRequestEntity(packet);
     postMethod.setRequestEntity(request);
     client.executeMethod(postMethod);
   } catch (IOException e) {
     return false;
   }
   return true;
 }
コード例 #27
0
 protected static PostMethod httpPost(String path, String body) throws IOException {
   LOG.info("Connecting to {}", url + path);
   HttpClient httpClient = new HttpClient();
   PostMethod postMethod = new PostMethod(url + path);
   postMethod.addRequestHeader("Origin", url);
   RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
   postMethod.setRequestEntity(entity);
   httpClient.executeMethod(postMethod);
   LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
   return postMethod;
 }
コード例 #28
0
 public void produceMessages() throws Exception {
   HttpClient client = new HttpClient();
   PostMethod method = new PostMethod(MessagingServiceMessagesURL);
   Base64 base64 = new Base64();
   String base64Credentials = new String(base64.encode("admin:admin".getBytes()));
   method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials));
   method.setRequestEntity(new StringRequestEntity("Hello !", "text/plain", "UTF-8"));
   int status = client.executeMethod(method);
   if (HttpResponseCodes.SC_OK != status) {
     throw new RuntimeException("Messages can not be sent");
   }
 }
コード例 #29
0
  /** Handles the HTTP post. Throws HttpException on failure */
  @SuppressWarnings("deprecation")
  private void doPost(PostMethod method, RequestEntity data, String dest)
      throws IOException, HttpException {

    HttpMethodParams pars = method.getParams();
    pars.setParameter(
        HttpMethodParams.RETRY_HANDLER,
        (Object)
            new HttpMethodRetryHandler() {
              public boolean retryMethod(HttpMethod m, IOException e, int exec) {
                return !(e instanceof java.net.ConnectException)
                    && (exec < MAX_RETRIES_PER_COLLECTOR);
              }
            });
    method.setParams(pars);
    method.setPath(dest);

    // send it across the network
    method.setRequestEntity(data);

    log.info("HTTP post to " + dest + " length = " + data.getContentLength());
    // Send POST request

    client.setTimeout(8000);
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      log.error(
          "HTTP post response statusCode: "
              + statusCode
              + ", statusLine: "
              + method.getStatusLine());
      // do something aggressive here
      throw new HttpException("got back a failure from server");
    }
    // implicitly "else"
    log.info(
        "got success back from the remote collector; response length "
            + method.getResponseContentLength());

    // FIXME: should parse acks here
    InputStream rstream = null;

    // Get the response body
    byte[] resp_buf = method.getResponseBody();
    rstream = new ByteArrayInputStream(resp_buf);
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
      System.out.println("response: " + line);
    }
  }
コード例 #30
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {

        JSONObject json =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));

        String contents = json.getString("names");

        byte[] fileContents = contents.getBytes("UTF-8");

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        GZIPOutputStream gzipStr = new GZIPOutputStream(byteArray);

        gzipStr.write(fileContents);
        gzipStr.close();

        ByteArrayOutputStream byteArray2 = new ByteArrayOutputStream();

        Base64OutputStream base64 = new Base64OutputStream(byteArray2);

        base64.write(byteArray.toByteArray());
        base64.close();

        String value = new String(byteArray2.toByteArray());

        json.remove("names");
        json.put("upload", value);

        HttpClient client = new HttpClient();

        PostMethod post =
            new PostMethod(
                "http://"
                    + properties.getProperty("org.iplantc.tnrs.servicesHost")
                    + "/tnrs-svc/upload");

        post.setRequestEntity(new StringRequestEntity(json.toString(), "text/plain", "UTF-8"));

        client.executeMethod(post);

        HandlerHelper.writeResponseRequest(arg0, 200, "", "text/plain");

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        ex.printStackTrace();
        throw new IOException(ex);
      }
    }