java 通过后端访问http并传参之post传参

String param= "{\n" +
        "\"signature\":\"1b811b104815e80dc06204769abf019454918820\",\n" +
        "\"timestamp\":\"636132491337817532\",\n" +
        "\"nonce\":\"0978730774\",\n" +
        "\"action\":\"GET_LIST\",\n" +
        "\"appid\":\"dsfew45432544dfs23q4rt5\",\n" +
        "\"accountname\":\"\",\n" +
        "\"data\":{\n" +
        "\"entity_type\":\"RESERVATION\",\n" +
        "\"pageindex\":0,\n" +
        "\"pagesize\":20,\n" +
        "\"query_condition\":{\n" +
        "\"starttime\":\"2015-1-31T16:00:00Z\",\n" +
        "\"endtime\":\"2018-12-31T16:00:00Z\",\n" +
        "\"key\":\"\",\n" +
        "\"name\":\"\"\n" +
        "}\n" +
        "}\n" +
        "}";
// 获取默认的请求客户端
CloseableHttpClient client = HttpClients.createDefault();
// 通过HttpPost来发送post请求
HttpPost httpPost = new HttpPost("http://10.10.20.114:8090/api/tt/post");
/*
 * post带参数开始
 */
// 第三步:构造list集合,往里面丢数据
List pairs = new ArrayList();
NameValuePair pair = new BasicNameValuePair("param", param);
pairs.add(pair);
// 第二步:我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
try {
    httpPost.setEntity(new UrlEncodedFormEntity(pairs,"utf8"));
    /*
     * post带参数结束
     */
    // HttpEntity
    // 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
    // 通过client来执行请求,获取一个响应结果
    CloseableHttpResponse response = client.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String str = EntityUtils.toString(entity, "UTF-8");
    System.out.println(str);
    // 关闭
    response.close();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

你可能感兴趣的:(java后端访问http)