程序類以post的方式(以json方式進行進行數據交換)調用其他微服務

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

//這個是楊恆的進行post調用的工具類。調用數據庫也是使用這個工具類
public class connectToOther {

    //private  final  static  String DBENGINEURL = "http://10.0.17.213:31380/public/api/dbengine/sql";
    private  final  static  String DBENGINEURL = "http://dbengine:9080/public/api/dbengine/sql";
    public static JSONObject doPost(String sql) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(DBENGINEURL);
        JSONObject jsonObject = new JSONObject();
        try {
            post.setHeader("Content-Type","application/json;charset=utf-8");
            post.setHeader("user","x");
            post.setHeader("key","x");
            JSONObject params= new JSONObject();
            params.put("sql",sql);
            StringEntity stringEntity = new StringEntity(params.toString(),Charset.forName("UTF-8"));
            post.setEntity(stringEntity);
            HttpResponse response = client.execute(post);
            String res = EntityUtils.toString(response.getEntity());
            jsonObject = JSONObject.parseObject(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}

還有一種方式在github上,不過歸根結底都已以CloseableHttpClient 類進行的操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章