Linux下Java发送post请求,header为application/x-www-form-urlencoded。

1.添加依赖

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

 

2.代码实现:

String url = "https://192.5.52.194:8868/nifi-api/access/token";

PostMethod postMethod = new PostMethod(url);

postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

NameValuePair[] data = {new NameValuePair("username", "test"), new NameValuePair("password", "123456")};

postMethod.setRequestBody(data);

HttpClient httpClient = new HttpClient();

int response = httpClient.executeMethod(postMethod);

String result = postMethod.getResponseBodyAsString();

3.访问https时出现unable to find valid certification path to requested target问题时,是因为本地没有安装访问url的相应的证书。可以在能访问到该网址的机器上使用chrome浏览器访问该地址,并点击如下所示的地址前面的小锁标识。

然后在弹出的证书框上点击详细信息,然后点击复制文件

导出文件格式选择Base64编码,将证书导出到本地,例如命名为key.cer

将该文件上传到linux机器的/opt目录下。注意java的证书验证系统是独立于操作系统和浏览器的,因此要将证书加到jre证书库中,执行以下命令,执行过程中数据Y即可。

keytool -import -keystore "/usr/java/jdk1.8.0_60/jre/lib/security/cacerts" -storepass changeit -keypass changeit -alias twca -file /opt/key.cer