HttpClient接口示例

HttpClient接口示例

httpcilent接口示例,话不多说 ,直接上代码,大家有问的直接留言或私信。

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.security.Security;


public class WeiXinFuWus {

    public static void main(String[] args) throws IOException {
        updateTagFans();
    }


    private static void updateTagFans() throws IOException {


        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost();
        try {

            httpClient = HttpClients.createDefault();
            httpPost.addHeader("Content-type", "application/json");

            //接口链接
            httpPost.setURI(URI.create("https://api.weixin.qq.com/cgi-bin/tags/update"));

            //json数据
            JSONObject jsonObject1 = new JSONObject();
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("name", "哈哈");
            jsonObject2.put("id", "123");
            jsonObject1.put("tag", jsonObject2);
            // json格式是   { "tag": { "id":"123", "name":"哈哈"} }

            StringEntity stringEntity = new StringEntity(jsonObject1.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            Security.addProvider(new BouncyCastleProvider());
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            //接口返回
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            httpClient.close();
        }

    }


}

欢迎大家私信或留言问题。

猜你喜欢

转载自blog.csdn.net/lzq_20120119/article/details/114029710