当前位置: 首页>>代码示例>>Java>>正文


Java RestTemplate.postForObject方法代码示例

本文整理汇总了Java中org.springframework.web.client.RestTemplate.postForObject方法的典型用法代码示例。如果您正苦于以下问题:Java RestTemplate.postForObject方法的具体用法?Java RestTemplate.postForObject怎么用?Java RestTemplate.postForObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.web.client.RestTemplate的用法示例。


在下文中一共展示了RestTemplate.postForObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAnswer

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public static String getAnswer(RestTemplate restTemplate, String question) {
    String url = "http://www.tuling123.com/openapi/api";
    HttpHeaders headers = new HttpHeaders();
    headers.add("Ocp-Apim-Subscription-Key", "3f5a37d9698744f3b40c89e2f0c94fb1");
    headers.add("Content-Type", "application/x-www-form-urlencoded");


    MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
    bodyMap.add("key", "e2e33efb4efb4e5794b48a18578384ee");
    bodyMap.add("info", question);


    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headers);
    String result = restTemplate.postForObject(url, requestEntity, String.class);
    return JsonPath.read(result, "$.text");
}
 
开发者ID:xjtushilei,项目名称:knowledge-forest-dialogue-recommendation,代码行数:17,代码来源:Tuling123.java

示例2: test

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
@Test
public void test() {
    
    RestTemplate rt = new RestTemplate();
    
    for (int i = 10; i< 100;i++) {
        System.out.println(i%2);
        RegistReq req = new RegistReq();
        req.setName("" + i);
        req.setSex(i%2);
        req.setPhone("0000" + i);
        req.setPassword(SecurityUtils.getInstance().EncryptPass("" + i));
        req.setEmail(i + "@hifipi.com");
        BaseModel res = rt.postForObject("http://tt.hifipi.com/regist", req, BaseModel.class);
        System.out.println(res.getCode());
    }
    
}
 
开发者ID:ccfish86,项目名称:sctalk,代码行数:19,代码来源:AccountSampleTest.java

示例3: testCodeFirstUserMap

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private void testCodeFirstUserMap(RestTemplate template, String cseUrlPrefix) {
  User user1 = new User();
  user1.setNames(new String[] {"u1", "u2"});

  User user2 = new User();
  user2.setNames(new String[] {"u3", "u4"});

  Map<String, User> userMap = new HashMap<>();
  userMap.put("u1", user1);
  userMap.put("u2", user2);

  @SuppressWarnings("unchecked")
  Map<String, User> result = template.postForObject(cseUrlPrefix + "testUserMap",
      userMap,
      Map.class);

  TestMgr.check("u1", result.get("u1").getNames()[0]);
  TestMgr.check("u2", result.get("u1").getNames()[1]);
  TestMgr.check("u3", result.get("u2").getNames()[0]);
  TestMgr.check("u4", result.get("u2").getNames()[1]);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:22,代码来源:CodeFirstRestTemplate.java

示例4: stopServer

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Stops the data server, gracefully if possible (using the /shutdown endpoint) otherwise forcibly.
 */
public static void stopServer() {
    logger.info("In DataServerManager.stopServer");

    try {
        // POST to Spring Boot shutdown handler to trigger a clean shutdown...
        // (it returns a short JSON reply message)
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(
                "http://localhost:9999/shutdown", null, String.class);
        logger.info("Server shutdown triggered, received {}", result);

    } catch (RestClientException ex) {
        String message = "Failed to post server shutdown message: " + ex.getMessage();
        logger.error(message, ex);

        if (serverProcess != null) {
            // attempt to kill the server process as a last resort...
            // not possible if using Courgette runner (as start and stop is in different processes)
            serverProcess.destroy();
            logger.info("Server process killed");
        }

        // swallow exception
    }
}
 
开发者ID:dvsa,项目名称:mot-automated-testsuite,代码行数:29,代码来源:DataServerManager.java

示例5: testModelFieldIgnore

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
protected void testModelFieldIgnore(RestTemplate template, String cseUrlPrefix) {
  InputModelForTestIgnore input = new InputModelForTestIgnore("input_id_rest", "input_id_content",
      new Person("inputSomeone"), new JsonObject("{\"InputJsonKey\" : \"InputJsonValue\"}"), () -> {
      });
  OutputModelForTestIgnore output = template
      .postForObject(cseUrlPrefix + "ignore", input, OutputModelForTestIgnore.class);

  TestMgr.check(null, output.getInputId());
  TestMgr.check(input.getContent(), output.getContent());
  TestMgr.check(null, output.getOutputId());

  TestMgr.check(null, output.getInputIgnoreInterface());
  TestMgr.check(null, output.getInputJsonObject());
  TestMgr.check(null, output.getInputObject());

  TestMgr.check(null, output.getOutputIgnoreInterface());
  TestMgr.check(null, output.getOutputJsonObject());
  TestMgr.check(null, output.getOutputObject());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:20,代码来源:CodeFirstRestTemplate.java

示例6: createFeedPost

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Create Feed Post
 * <p>
 * Requires the Twitch *channel_feed_edit* Scope.
 *
 * @param credential  OAuth token for a Twitch user (that as 2fa enabled)
 * @param channelId Channel ID
 * @param message message to feed
 * @param share Share to Twitter if is connected
 */
public void createFeedPost(OAuthCredential credential, Long channelId, String message, Optional<Boolean> share) {
	// Endpoint
	String requestUrl = String.format("%s//feed/%s/posts", Endpoints.API.getURL(), channelId);
	RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential);

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("share", share.orElse(false).toString()));

	// Post Data
	MultiValueMap<String, Object> postBody = new LinkedMultiValueMap<String, Object>();
	postBody.add("content", message);

	// REST Request
	try {
		restTemplate.postForObject(requestUrl, postBody, Void.class);
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:33,代码来源:ChannelFeedEndpoint.java

示例7: updateCommunity

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Endpoint: Update Community
 * Creates a community.
 * Requires Scope: none
 *
 * @param credential  OAuth token for a Twitch user (that as 2fa enabled)
 * @param id          Id of the community, which will be updated.
 * @param name        Community name. 3-25 characters, which can be alphanumerics, dashes (-), periods (.), underscores (_), and tildes (~). Cannot contain spaces.
 * @param summary     Short description of the community, shown in search results. Maximum: 160 characters.
 * @param description Long description of the community, shown in the *about this community* box. Markdown syntax allowed. Maximum 1,572,864 characters (1.5 MB).
 * @param rules       Rules displayed when viewing a community page or searching for a community from the broadcaster dashboard. Markdown syntax allowed. Maximum 1,572,864 characters (1.5 MB)
 * @param email       Email address of the community owner.
 */
public void updateCommunity(OAuthCredential credential, String id, Optional<String> name, Optional<String> summary, Optional<String> description, Optional<String> rules, Optional<String> email) {
	// Endpoint
	String requestUrl = String.format("%s/communities/%s", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Post Data
	MultiValueMap<String, Object> postBody = new LinkedMultiValueMap<String, Object>();
	postBody.add("summary", summary.orElse(""));
	postBody.add("description", description.orElse(""));
	postBody.add("rules", rules.orElse(""));
	postBody.add("email", email.orElse(""));

	// REST Request
	try {
		restTemplate.postForObject(requestUrl, postBody, CommunityCreate.class);
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return;
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:38,代码来源:CommunityEndpoint.java

示例8: testCodeFirstAddDate

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private void testCodeFirstAddDate(RestTemplate template, String cseUrlPrefix) {
  Map<String, Object> body = new HashMap<>();
  Date date = new Date();
  body.put("date", date);

  int seconds = 1;
  Date result = template.postForObject(cseUrlPrefix + "addDate?seconds={seconds}",
      body,
      Date.class,
      seconds);
  TestMgr.check(new Date(date.getTime() + seconds * 1000), result);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:13,代码来源:CodeFirstRestTemplate.java

示例9: attemptToCreateService

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private void attemptToCreateService(CloudFoundryOperations client, CloudServiceExtended service, String spaceId) {
    assertServiceAttributes(service);

    RestTemplate restTemplate = getRestTemplate(client);
    String cloudControllerUrl = client.getCloudControllerUrl().toString();
    CloudServicePlan cloudServicePlan = findPlanForService(service, restTemplate, cloudControllerUrl);

    Map<String, Object> serviceRequest = createServiceRequest(service, spaceId, cloudServicePlan);
    restTemplate.postForObject(getUrl(cloudControllerUrl, CREATE_SERVICE_URL_ACCEPTS_INCOMPLETE_FALSE), serviceRequest, String.class);
}
 
开发者ID:SAP,项目名称:cf-mta-deploy-service,代码行数:11,代码来源:ServiceCreator.java

示例10: testCodeFirstSayHello

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
protected void testCodeFirstSayHello(RestTemplate template, String cseUrlPrefix) {
  Map<String, String> persionFieldMap = new HashMap<>();
  persionFieldMap.put("name", "person name from map");
  Person result = template.postForObject(cseUrlPrefix + "sayhello", persionFieldMap, Person.class);
  TestMgr.check("hello person name from map", result);

  Person input = new Person();
  input.setName("person name from Object");
  result = template.postForObject(cseUrlPrefix + "sayhello", input, Person.class);
  TestMgr.check("hello person name from Object", result);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:12,代码来源:CodeFirstRestTemplate.java

示例11: testCodeFirstAdd

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
protected void testCodeFirstAdd(RestTemplate template, String cseUrlPrefix) {
  Map<String, String> params = new HashMap<>();
  params.put("a", "5");
  params.put("b", "3");
  int result =
      template.postForObject(cseUrlPrefix + "add", params, Integer.class);
  TestMgr.check(8, result);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:9,代码来源:CodeFirstRestTemplate.java

示例12: testRestTemplateUpload

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
private String testRestTemplateUpload(RestTemplate template, String cseUrlPrefix, File file1, File someFile) {
  MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
  map.add("file1", new FileSystemResource(file1));
  map.add("someFile", new FileSystemResource(someFile));

  return template.postForObject(
      cseUrlPrefix + "/upload",
      new HttpEntity<>(map),
      String.class);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:11,代码来源:CodeFirstRestTemplateSpringmvc.java

示例13: saveSession

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void saveSession(long userId, long sessionDuration, String task) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
    TimedSession timedSession = new TimedSession(userId, sessionDuration, task, simpleDateFormat.format(new Date()));
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<TimedSession> request = new HttpEntity<>(timedSession);

    try {
        restTemplate.postForObject(BASE_URL + "/session/save", request, TimedSession.class);
    } catch (RestClientException e) {
        throw new ServerUnreachableException("Server unreachable");
    }
}
 
开发者ID:softish,项目名称:KetchupDesktop,代码行数:13,代码来源:APIDriver.java

示例14: getOAuthToken

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
/**
 * Gets/refreshes the token
 *
 * @param grant_type Valid values: authorization_code or refresh_token.
 * @param redirect_url Redirect url.
 * @param code authentication_code or refresh_token
 * @return {@link Authorize} data on {@link Optional} container class
 */
public Optional<Authorize> getOAuthToken(String grant_type, String redirect_url, String code) {
	// Endpoint
	String requestUrl = String.format("%s/oauth2/token", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Post Data
	MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<String, Object>();
	postParameters.add("grant_type", grant_type);
	postParameters.add("client_id", getTwitchClient().getClientId());
	postParameters.add("client_secret", getTwitchClient().getClientSecret());
	postParameters.add("redirect_uri", redirect_url);
	if(grant_type.equals("authorization_code")) {
		postParameters.add("code", code);
	} else if(grant_type.equals("refresh_token")) {
		postParameters.add("refresh_token", code);
	}

	// REST Request
	try {
		Authorize responseObject = restTemplate.postForObject(requestUrl, postParameters, Authorize.class);

		return Optional.ofNullable(responseObject);
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		ex.printStackTrace();
	}

	return Optional.empty();
}
 
开发者ID:twitch4j,项目名称:twitch4j,代码行数:39,代码来源:KrakenEndpoint.java

示例15: run

import org.springframework.web.client.RestTemplate; //导入方法依赖的package包/类
public void run() throws Exception {
    final File file = new File(inputFile);

    if (!file.exists() || !file.isFile()) {
        System.err.format("unable to access file %s\n", inputFile);
        System.exit(2);
    }

    // Open file
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    // Initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();

    if (textAsJson) {
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
        converters.add(new ExtendedMappingJackson2HttpMessageConverter());
        restTemplate.setMessageConverters(converters);
    }

    // Read each line
    String line = null;
    while ((line = br.readLine()) != null) {
        // Check if label indicator is up front
        String label = null;
        if (line.matches("^\\d:\\s.*")) {
            label = line.substring(0, 1);
        }

        // Just in case
        line = StringUtils.removePattern(line, "^\\d:\\s");
        String[] fields = line.split(",");

        // Maybe strip quotes
        for (int i = 0; i < fields.length; i++) {
            final String field = fields[i];
            if (field.matches("^\".*\"$")) {
                fields[i] = field.substring(1, field.length() - 1);
            }
        }

        int[] shape = (isSequential) ?
                new int[] { 1, 1, fields.length} :
                new int[] { 1, fields.length};

        INDArray array = Nd4j.create(shape);

        for (int i=0; i<fields.length; i++) {
            // TODO: catch NumberFormatException
            Double d = Double.parseDouble(fields[i]);
            int[] idx = (isSequential) ?
                    new int[]{0, 0, i} :
                    new int[]{0, i};

            array.putScalar(idx, d);
        }

        Inference.Request request = new Inference.Request(Nd4jBase64.base64String(array));
        final Object response = restTemplate.postForObject(
                inferenceEndpoint,
                request,
                Inference.Response.Classify.class);

        System.out.format("Inference response: %s\n", response.toString());
        if (label != null) {
            System.out.format("  Label expected: %s\n", label);
        }
    }

    br.close();
}
 
开发者ID:SkymindIO,项目名称:SKIL_Examples,代码行数:72,代码来源:ModelServerDirectInferenceExample.java


注:本文中的org.springframework.web.client.RestTemplate.postForObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。