Java HTTP POST请求与CURL

时间:2015-03-02 14:10:25

标签: java http post curl

如何翻译以下内容:

curl -X POST -d 'param1=value1&param2=value2' http://url/get_file
在Java中

我尝试如下,但这不起作用,请求格式不正确。

HttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("http://url/get_file");

try {
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("param1", value1));
    params.add(new BasicNameValuePair("param2", value2));
    request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        instream.close();
    }
}
catch (IOException e) {
    e.printStackTrace();
}

0 个答案:

没有答案