當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。