依赖的jar包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
代码实现,是否push成功可以在agent的日志中查看。
package agent;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
public class App
{
public static void main( String[] args ) throws Exception
{
while (true) {
Test();
Thread.sleep(5000);
}
}
public static void Test() {
try {
HttpClient client = new DefaultHttpClient( );
HttpPost post = new HttpPost("http://192.168.1.127:1988/v1/push");
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("endpoint","ubuntu");
map.put("metric","testmetric2018.02.06java");
map.put("timestamp",System.currentTimeMillis()/1000);
map.put("step", 60);
map.put("value", 100.0);
map.put("counterType", "GAUGE");
map.put("tags","idc=lg,loc=shanghai");
StringEntity stringEntity = null;
stringEntity = new StringEntity("["+ JSON.toJSONString(map)+"]");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
//debug
System.out.println(stringEntity);
System.out.println(JSON.toJSONString(map));
//debug
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
}
}catch (Exception e) {
System.out.println(e);
}
}
}