繁体   English   中英

使用HttpClient和HttpMethod放入带内容的请求

[英]Put Request with Content with HttpClient and HttpMethod

我使用HttpClient和HttpMethod来触发我的REST服务但是如果我想给put方法一些内容,它就不起作用了。 该服务在webservcer上是tiriggered但内容为null。

public boolean putter(String url, String entity) {
        httpClient = new HttpClient();
        Credentials defaultcreds = new UsernamePasswordCredentials("user", "pw");
        httpClient.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
        uri = "http://localhost:59189/v1/";
        HttpMethod method = new PutMethod(uri + url);
        try {
            HttpPut putRequest = new HttpPut(uri + url);
            putRequest.setHeader("Content-Type", "application/json");

            if (entity != null) {
                StringEntity ent = new StringEntity(entity);
                if (entityContentType != null) {
                    ent.setContentType(entityContentType.toString());
                }
                putRequest.setEntity(ent);
            }
            httpClient.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }

        return false;
    }

这就是我正在做的不仅仅是在身体上发布一个带有json的帖子,而是用修改后的身体回答请求

HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(json.toString(), headers);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responsee =null;
    try{
        responsee = restTemplate.postForEntity( "http://localhost:59189/v1/", request , String.class );
    }catch (HttpClientErrorException e){
        return ResponseEntity.status(401)
                .body("usuario não encontrado");
    }

使用的库

import org.springframework.http。 ;
import org.springframework.web.bind.annotation。 ;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletResponse;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM