linux系统中使用curl工具发送http的put请求可以访问到web服务器的数据,其中curl的命令如下:
curl -v --basic -u admin:public -k http://localhost:8080/api/v2/nodes/emq@127.0.0.1/plugins/emqx_recon -X PUT -i -H "Conten
t-Type:application/json" -d '{"active":"true"}'
使用此命令可以有反馈的json结果,表示已经处理。
而在linux下开发环境eclipse使用httpclient发送http的put请求,数据是json数据,却一直报错,不清楚什么原因,贴上代码:
public String doPutMethod(String host, int port, String URI,String stringJson){
if (closeableHttpClient == null) {
// createCloseableHttpClient();
createCloseableHttpClientWithBasicAuth();
}
String result = "";
HttpPut httpPut = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
httpPut = new HttpPut("http://" + host + ":" + port + "/" + URI);
//设置header
httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPut.setHeader("Accept", "application/json");
StringEntity stringEntity = null;
stringEntity = new StringEntity(stringJson,ContentType.APPLICATION_JSON);
stringEntity.setContentEncoding("UTF-8");
System.out.println(stringEntity.getContentType());
System.out.println(stringEntity.getContentEncoding());
try {
System.out.println(EntityUtils.toString(stringEntity));
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
httpPut.setEntity(stringEntity);
try {
httpResponse = closeableHttpClient.execute(httpPut);
entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPut.releaseConnection();
}
return result;
}
public static void main(String args[]) {
String host = "localhost";
int port = 8080;
HttpClientWithBasicAuth httpClient = new HttpClientWithBasicAuth();
//test httpPutMethod
String URI = "api/v2/nodes/emq@127.0.0.1/plugins/emq_auth_clientid";
String str = "{\"active\":\"true\"}";
String result = httpClient.doPutMethod(host, port, URI, str);
System.out.println(result);
}