注意param为json格式的字符串
public static String doPost(String url,String param){
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
try{
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(param);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(),"utf-8");
}catch (Exception e){
e.printStackTrace();
}finally {
if(response != null){
try {
response.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
if(httpClient != null){
try{
httpClient.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
return result;
}
需要导入的依赖有:
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
|