天天看点

httpclient post 发送 param 和 body

package com.example.demo.webservice;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;

import java.io.IOException;

public class HttpClientUtil {
    public static void post(String url, String bodyJson) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setEntity(new StringEntity(bodyJson, "utf-8"));
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println("发送post成功");
            }
        } catch (Exception e) {
            System.out.println("发送post失败");
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) {
        String url = "http://10.137.123.61:8095/api/v1/tpaService/licardinfolog/saveInfo?tpa=sbt&resultCode=1";
        String json = "{\"online\":\"00000\",\"id\":\"123\"}";
        post(url, json);
    }
}