添加一個api,curl命令以下:java
[root@dscn1 hadmin]# curl -i -X POST \
> -url http://localhost:29976/apis/ \
> -d 'name=ein123' \
> -d 'upstream_url=http://192.168.1.14:3333' \
> -d 'request_host=ein123.com' \
> -d 'strip_request_path=true' \
> -d 'request_path=/ein123'json
那對應的java代碼以下:api
public static void postTest() throws Exception { CloseableHttpClient client = HttpClients.createDefault(); String url = "http://192.168.1.45:29976/apis/"; HttpPost post = new HttpPost(url); JSONObject arg = new JSONObject(); arg.put("name", "ein123"); arg.put("upstream_url", "http://192.168.1.14:3333"); arg.put("request_host", "ein123.com"); arg.put("strip_request_path", "true"); arg.put("request_path", "/ein123"); StringEntity reqEntity = new StringEntity(arg.toString()); reqEntity.setContentType("application/json"); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String message = EntityUtils.toString(entity, "UTF-8"); System.out.println(message); }
對於post請求,請求參數都是放在body裏,因此用stringentity來封裝一下app
返回信息:curl
{"upstream_url":"http:\/\/192.168.1.14:3333","strip_request_path":true,"request_path":"\/ein123","id":"2af74deb-d26d-4800-b718-3ddca0bcc068","created_at":1484119862000,"preserve_host":false,"name":"ein123","request_host":"ein123.com"}post
這樣就成功了url