向webservice发出POST请求

时间:2014-11-05 20:13:52

标签: java web-services

我正在尝试向网络服务发布帖子请求,因为它只接受帖子请求。我有一个代码

try {
        URL url = new URL(createBookUrl + "?bookInfo=" + jsonStr);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine = in.readLine();
        in.close();
        BookCreateResponse bookCreateResponse = new BookCreateResponse ();
        ObjectMapper mapper = new ObjectMapper();
        bookCreateResponse = mapper.readValue(inputLine, new TypeReference<BookCreateResponse>(){});
        System.out.println(bookCreateResponse );
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }

现在我收到错误

Server returned HTTP response code: 405 for URL: .....

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

    private HttpClient client;
    private HttpPost requestPost;

    client = HttpClientBuilder.create().build();


    requestPost = new HttpPost(url+params);
    HttpResponse response = client.execute(requestPost);
    HttpEntity entiry = response.getEntity();
    responseString = EntityUtils.toString(entiry, "UTF-8");