public String refreshToken(String refresh_token){
		
		String response = null;
		
		String Client_id = AppConfig.APP_ID;
		String Client_secret = AppConfig.APP_SECRET;
		String Url = "https://graph.renren.com/oauth/token?"+
		    "grant_type=refresh_token&"+
		    "refresh_token="+refresh_token+"&"+
		    "client_id="+Client_id+"&"+
		    "client_secret="+Client_secret;
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod (Url);
		
		try{
			client.executeMethod(method);
			if(method.getStatusCode()== HttpStatus.SC_OK){
				response = method.getResponseBodyAsString();
			}
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println("Exception happend when processing Http Post:"+Url+"\n"+e);
		}finally{
			method.releaseConnection();
		}
		System.out.println("[FeedStub : run]"+response);
		
		net.sf.json.JSONArray jsonarray = net.sf.json.JSONArray.fromObject(response);
		net.sf.json.JSONObject jsonobject = jsonarray.getJSONObject(0);
		
		return (String) jsonobject.get("access_token");
	}
Esempio n. 2
0
  /**
   * 单次上传图片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("服务器状态异常");
    }
  }
Esempio n. 3
0
  public static String getHttp(String url, Boolean all) throws HttpException, Exception {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        throw new HttpException("访问失败,错误原因:" + method.getStatusLine());
      }

      InputStream response = method.getResponseBodyAsStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
      if (all) {
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
          sb.append(str);
          sb.append("\r\n");
        }

        return sb.toString();
      } else {
        return br.readLine();
      }
    } finally {
      method.releaseConnection();
    }
  }
Esempio n. 4
0
 private HttpMethod redirectMethod(PostMethod postMethod) {
   GetMethod method = new GetMethod(postMethod.getResponseHeader("Location").getValue());
   for (Header header : postMethod.getRequestHeaders()) {
     method.addRequestHeader(header);
   }
   return method;
 }
Esempio n. 5
0
 public String getHtmlByParamAndCode(NameValuePair[] param, String code) {
   StringBuffer contentStr = new StringBuffer();
   PostMethod postMethod = null;
   init();
   try {
     postMethod = new PostMethod(this.getUrl());
     postMethod.setRequestBody(param);
     postMethod.setRequestHeader(
         "User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); // ä¯ÀÀÆ÷αÔì
     client.executeMethod(postMethod);
     InputStream in = postMethod.getResponseBodyAsStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in, code), 1024);
     String line = "";
     while ((line = br.readLine()) != null) {
       contentStr.append(line);
     }
     if (br != null) {
       br.close();
       br = null;
     }
     if (in != null) {
       in.close();
       in = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     release();
   } finally {
     postMethod.releaseConnection();
   }
   return contentStr.toString();
 }
Esempio n. 6
0
  /** 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);
  }
  public String jasperAuthen(String username, String password) throws HttpException, IOException {
    logger.info("Authenticate : Jasper Report Server");

    Header[] headers = null;
    String sessionCookie = "";

    this.httpClient = new HttpClient();
    PostMethod mPost = new PostMethod(restLoginUrl);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    mPost.addParameter("j_username", username);
    mPost.addParameter("j_password", password);
    mPost.addRequestHeader(mtHeader);

    httpClient.executeMethod(mPost);

    headers = mPost.getResponseHeaders();
    mPost.releaseConnection();

    sessionCookie = headers[2].getValue();
    logger.debug("SessionCookie is {}", sessionCookie);

    return sessionCookie;
  }
Esempio n. 8
0
  @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;
  }
Esempio n. 9
0
  public static String postXml(String url, String xml) {
    String txt = null;
    PostMethod post = new PostMethod(url); // 请求地址
    post.setRequestBody(xml); // 这里添加xml字符串

    // 指定请求内容的类型
    post.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1");
    HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例
    int result;
    try {
      result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result); // 返回200为成功
      System.out.println("Response body: ");

      BufferedReader reader =
          new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "ISO-8859-1"));
      String tmp = null;
      String htmlRet = "";
      while ((tmp = reader.readLine()) != null) {
        htmlRet += tmp + "\r\n";
      }
      txt = new String(htmlRet.getBytes("ISO-8859-1"), "UTF-8");
      System.out.println(txt);

      // txt = post.getResponseBodyAsString();
      // System.out.println(post.getResponseBodyAsString());// 返回的内容
      post.releaseConnection(); // 释放连接
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return txt;
  }
Esempio n. 10
0
 /**
  * Attempt to POST contents of support request form to {@link #requestUrl}.
  *
  * @throws WrapperException if there was a problem on the server.
  */
 protected String compute() {
   // logic ripped from the IDV's HttpFormEntry#doPost(List, String)
   try {
     while ((tryCount++ < POST_ATTEMPTS) && !isCancelled()) {
       method = buildPostMethod(validFormUrl, form);
       HttpClient client = new HttpClient();
       client.executeMethod(method);
       if (method.getStatusCode() >= 300 && method.getStatusCode() <= 399) {
         Header location = method.getResponseHeader("location");
         if (location == null) {
           return "Error: No 'location' given on the redirect";
         }
         validFormUrl = location.getValue();
         if (method.getStatusCode() == 301) {
           logger.warn("form post has been permanently moved to: {}", validFormUrl);
         }
         continue;
       }
       break;
     }
     return IOUtil.readContents(method.getResponseBodyAsStream());
   } catch (Exception e) {
     throw new WrapperException(POST_ERROR, e);
   }
 }
 @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();
     }
   }
 }
Esempio n. 12
0
  public static void fetchNextPage(Integer pageNo, HttpClient client) throws Exception {
    NameValuePair[] data = {
      new NameValuePair(
          "User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:25.0) Gecko/20100101 Firefox/25.0"),
      new NameValuePair("__EVENTARGUMENT", ""),
      new NameValuePair("__EVENTTARGET", ""),
      new NameValuePair("__VIEWSTATE", viewState),
      new NameValuePair("__EVENTVALIDATION", eventValidation),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24ImplementDayDDList", "0"),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24ImplementMonthDDList", "0"),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24PropertyDDL", "2"),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24PublishedDayDDList", "0"),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24PublishedMonthDDList", "0"),
      new NameValuePair("ctl00$ContentPlaceHolder1$btnNext.x", btn_x),
      new NameValuePair("ctl00$ContentPlaceHolder1$btnNext.y", btn_y),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24pageNo", ""),
      new NameValuePair("ctl00%24ContentPlaceHolder1%24statusDDList", "2"),
      new NameValuePair(
          "ctl00_ContentPlaceHolder1_categoryTreeView_ExpandState",
          "enennnnnnnnnnnnnnnnnnnnnnnnnnnn")
    };

    PostMethod post = new PostMethod("http://www.catarc.org.cn/standard/SearchStandard.aspx");
    post.setRequestBody(data);
    client.executeMethod(post);

    String html = post.getResponseBodyAsString();

    setViewState(html);

    setEventValidation(html);

    setStandardIdsToMap(pageNo, html);
  }
Esempio n. 13
0
  public String getContextByPostMethod(String url, List<KeyValue> params) {
    HttpClient client = getHttpClient();

    client.getParams().setParameter("http.protocol.content-charset", this.codeing);

    PostMethod post = null;
    String result = "";
    try {
      URL u = new URL(url);
      client
          .getHostConfiguration()
          .setHost(
              u.getHost(), u.getPort() == -1 ? u.getDefaultPort() : u.getPort(), u.getProtocol());

      post = new PostMethod(u.getPath());

      NameValuePair[] nvps = new NameValuePair[params.size()];
      int i = 0;
      for (KeyValue kv : params) {
        nvps[i] = new NameValuePair(kv.getKey(), kv.getValue());
        i++;
      }

      post.setRequestBody(nvps);

      client.executeMethod(post);
      result = post.getResponseBodyAsString();
    } catch (Exception e) {
      throw new NetException("HttpClient catch!", e);
    } finally {
      if (post != null) post.releaseConnection();
    }
    return result;
  }
Esempio n. 14
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();
   }
 }
Esempio n. 15
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;
 }
  private static JSONObject open(String host, int port) throws Exception {
    JSONObject result;
    PostMethod method = new PostMethod(host + ":" + port + "/api/data/store.open");

    // client.getState().setCredentials(new AuthScope(null, repoHostPort, "authentication"), new
    // UsernamePasswordCredentials(memberId, memberPassword));

    // method.setDoAuthentication(true);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
    }

    Reader reader = new InputStreamReader(method.getResponseBodyAsStream());
    CharArrayWriter cdata = new CharArrayWriter();
    char buf[] = new char[BUFFER_SIZE];
    int ret;
    while ((ret = reader.read(buf, 0, BUFFER_SIZE)) != -1) cdata.write(buf, 0, ret);

    reader.close();

    result = JSONObject.fromString(cdata.toString());

    method.releaseConnection();

    if (result.has("error")) throw new GeneralException(result.getString("error"));

    return result;
  }
  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();
  }
  @Test
  public void shouldSetBodyParametersForPOSTRequestType() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("key1", "value1");
    params.put("key2", "value2");
    params.put("recipients", "$recipients");
    params.put("message", "$message");
    Request request =
        new SmsSendTemplateBuilder.RequestBuilder()
            .withType(HttpMethodType.POST)
            .withBodyParameters(params)
            .withRecipientSeperator(",")
            .build();

    SmsHttpTemplate smsHttpTemplate = createSmsHttpTemplate(request);

    PostMethod httpMethod =
        (PostMethod)
            smsHttpTemplate.generateRequestFor(Arrays.asList("123", "456", "789"), "someMessage");
    assertEquals(4, httpMethod.getParameters().length);
    assertEquals("value1", httpMethod.getParameter("key1").getValue());
    assertEquals("value2", httpMethod.getParameter("key2").getValue());
    assertEquals("123,456,789", httpMethod.getParameter("recipients").getValue());
    assertEquals("someMessage", httpMethod.getParameter("message").getValue());
  }
Esempio n. 19
0
  public static void send(String content, String mobile) throws Exception {

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(Url);

    client.getParams().setContentCharset("UTF-8");
    method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");

    NameValuePair[] data = { // 提交短信
      new NameValuePair("account", "cf_ddz"),
      new NameValuePair("password", "zaq12wsx"), // 密码可以使用明文密码或使用32位MD5加密
      new NameValuePair("mobile", mobile),
      new NameValuePair("content", content),
    };

    method.setRequestBody(data);

    client.executeMethod(method);

    String SubmitResult = method.getResponseBodyAsString();

    Document doc = DocumentHelper.parseText(SubmitResult);
    Element root = doc.getRootElement();

    String code = root.elementText("code");
    String msg = root.elementText("msg");
    String smsid = root.elementText("smsid");

    logger.info(code + "|" + msg + "|" + smsid);
  }
Esempio n. 20
0
  /**
   * Method responsible for querying and parsing to correios cep locator
   *
   * @author pulu - 09/09/2013
   */
  private Webservicecep findAddressByCepAtCorreios(String url) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    log.log(Level.INFO, "Querying to correios WS...");
    try {
      httpClient.executeMethod(postMethod);

      if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
        Document doc = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url);
        Elements elements = doc.select("td:not([colspan]):not(:has(*))");

        return new Webservicecep(
            Webservicecep.SUCCESS_CODE,
            elements.get(3).ownText(),
            elements.get(2).ownText(),
            elements.get(1).ownText(),
            "",
            elements.get(0).ownText());

      } else return new Webservicecep(Webservicecep.ERROR_CODE);
    } catch (Exception e) {
      log.log(Level.WARNING, "Failed to parse html data. Possible reason: invalid cep.");
      return new Webservicecep(Webservicecep.ERROR_CODE);
    }
  }
Esempio n. 21
0
 /**
  * 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);
   }
 }
  @Test
  public void testPOSTObject() throws Exception {
    final String TAG_VALUE = "TAG";

    Property property = new Property();
    property.setName("tags");
    property.setValue(TAG_VALUE);
    Object object = objectFactory.createObject();
    object.setClassName("XWiki.TagClass");
    object.getProperties().add(property);

    PostMethod postMethod =
        executePostXml(
            getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
            object,
            "Admin",
            "admin");
    Assert.assertEquals(
        getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());

    GetMethod getMethod =
        executeGet(
            getUriBuilder(ObjectResource.class)
                .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber())
                .toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());
  }
Esempio n. 23
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();
   }
 }
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    GetMethod getMethod =
        executeGet(
            getUriBuilder(PageResource.class).build(getWiki(), "Main", "WebHome").toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    Page page = (Page) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
    Link link = getFirstLinkByRelation(page, Relations.OBJECTS);

    /* Create a tag object if it doesn't exist yet */
    if (link == null) {
      Object object = objectFactory.createObject();
      object.setClassName("XWiki.TagClass");

      PostMethod postMethod =
          executePostXml(
              getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
              object,
              "Admin",
              "admin");
      Assert.assertEquals(
          getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());
    }
  }
Esempio n. 25
0
  /**
   * 批量上传图片
   *
   * @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;
    }
  }
  @Test
  public void testPOSTObjectFormUrlEncoded() throws Exception {
    final String TAG_VALUE = "TAG";

    NameValuePair[] nameValuePairs = new NameValuePair[2];
    nameValuePairs[0] = new NameValuePair("className", "XWiki.TagClass");
    nameValuePairs[1] = new NameValuePair("property#tags", TAG_VALUE);

    PostMethod postMethod =
        executePostForm(
            getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
            nameValuePairs,
            "Admin",
            "admin");
    Assert.assertEquals(
        getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());

    Object object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());

    GetMethod getMethod =
        executeGet(
            getUriBuilder(ObjectResource.class)
                .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber())
                .toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());
  }
 /** Process the result got from data sources. */
 @Override
 public void processResult(Operation operation, Object resultObj, Map<String, Object> keyMap)
     throws BaseCollectionException {
   // TODO Auto-generated method stub
   _logger.info("Processing VNX Mount Query response: {}", resultObj);
   final PostMethod result = (PostMethod) resultObj;
   try {
     ResponsePacket responsePacket =
         (ResponsePacket) _unmarshaller.unmarshal(result.getResponseBodyAsStream());
     // Extract session information from the response header.
     Header[] headers = result.getResponseHeaders(VNXFileConstants.CELERRA_SESSION);
     if (null != headers && headers.length > 0) {
       keyMap.put(VNXFileConstants.CELERRA_SESSION, headers[0].getValue());
       _logger.info("Received celerra session info from the Server.");
     }
     if (null != responsePacket.getPacketFault()) {
       Status status = responsePacket.getPacketFault();
       processErrorStatus(status, keyMap);
     } else {
       List<Object> mountList = getQueryResponse(responsePacket);
       // process the mount list
       processMountList(mountList, keyMap);
       keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_SUCCESS);
     }
   } catch (final Exception ex) {
     _logger.error(
         "Exception occurred while processing the vnx fileShare response due to {}",
         ex.getMessage());
     keyMap.put(VNXFileConstants.FAULT_DESC, ex.getMessage());
     keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_FAILURE);
   } finally {
     result.releaseConnection();
   }
   return;
 }
Esempio n. 28
0
  public static String postRequest(String url, Map<String, String> parameters) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    if (MapUtils.isNotEmpty(parameters)) {
      NameValuePair[] pairs = new NameValuePair[parameters.size()];
      Iterator<Entry<String, String>> iterator = parameters.entrySet().iterator();
      int index = 0;
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
        pairs[index++] = new NameValuePair(entry.getKey(), entry.getValue());
      }
      method.setRequestBody(pairs);
    }

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("post method fail.url={},status={}", url, statusCode);
        return "";
      }
      byte[] responseBody = method.getResponseBody();
      return new String(responseBody, "UTF-8");
    } catch (Exception e) {
      logger.error("url=" + url, e);
      return "";
    } finally {
      method.releaseConnection();
    }
  }
Esempio n. 29
0
  public synchronized void updateHtmlEntry(String key, String html) throws HttpException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(catalogDbURL + "update");
    System.err.println(key);
    postMethod.addParameter("key", key);
    postMethod.addParameter("columns", html);
    try {
      httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
      try {
        String resp = postMethod.getResponseBodyAsString();
        System.err.println(resp);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      throw new HttpException("failed to post form.");
    }
  }
Esempio n. 30
0
  @Action("SignModeCheck")
  public String signModeCheck() throws Exception {
    try {
      HttpClient client = new HttpClient();
      String url = "http://127.0.0.1:" + getServerPort() + "/service/";
      logger.debug("url: " + url);

      CommunicationVo requestVo = new CommunicationVo();
      requestVo.setTradeCode("000001");
      requestVo.putParam("signMode", this.signVo.getSignMode());
      requestVo.putParam("certDn", this.signVo.getCertDn());
      PostMethod postMethod = new PostMethod(url);
      postMethod.addParameter("json", requestVo.toJson());

      client.executeMethod(postMethod);

      String resp = postMethod.getResponseBodyAsString().trim();

      postMethod.releaseConnection();
      logger.info("resp: " + resp);

      CommunicationVo respVo = CommunicationVo.getInstancefromJson(resp);
      if (!"0000".equals(respVo.getStatus())) {
        throw new ServiceException(respVo.getMessage());
      }
      this.dwzResp.ajaxSuccessForward(respVo.getMessage());
      this.dwzResp.setAlertClose(Boolean.valueOf(false));
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      this.dwzResp.errorForward(e.getMessage());
      return "dwz";
    }
    return "dwz";
  }