Java学习

Java下Apache的HttpClient发送Get、Post

2020-08-10  本文已影响0人  xiaogp

使用flask创建api接口, flask使用jsonify返回需要增加编码配置

app.config['JSON_AS_ASCII'] = False

请求实例如下

>>> import requests
>>> # get请求
>>> res = requests.get("http://0.0.0.0:5001/synonym?text=福建青松股份有限公司")
>>> res.json()
{'code': 200, 'msg': 'success', 'res': '青松股份'}
>>>
>>> # json post请求
>>> res = requests.post("http://0.0.0.0:5001/synonym", json={"text": "福建青松股份有限公司"})
>>> res.json()
>>>
>>> # 表单post请求
>>> res = requests.post("http://0.0.0.0:5001/synonym", data={"text": "福建青松股份有限公司"})
>>> res.json()
{'code': 200, 'msg': 'success', 'res': '青松股份'}

引入依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>

调用api请求测试

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;


public class HttpTets {
    public static void main(String[] args) {
        // get请求
        JSONObject res1 = get("http://0.0.0.0:5001/synonym?text=福建青松股份有限公司");
        System.out.println(res1.toString());
        System.out.println(res1.getString("res"));
        // post请求 json
        post("http://0.0.0.0:5001/synonym", "{\"text\": \"福建青松股份有限公司\"}");
        JSONObject res2 = post2("http://192.168.67.72:5001/synonym", "{\"text\": \"福建青松股份有限公司\"}");
        System.out.println(res2.toString());
        System.out.println(res2.getString("res"));
        // post请求 form
        JSONObject res3 = post3("http://0.0.0.0:5001/synonym", "福建青松股份有限公司");
        System.out.println(res3.toString());
        System.out.println(res3.getString("res"));

    }

    /*
    get请求
     */
    public static JSONObject get(String url) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        String data = null;
        try {
            HttpResponse response = client.execute(request);
            data = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return JSON.parseObject(data);
    }


    /*
    post请求json
     */
    public static void post(String url, String jsonString) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity requestEntity = new StringEntity(jsonString, "UTF-8");
            requestEntity.setContentEncoding("utf-8");
            post.setHeader("Content-type", "application/json");
            post.setEntity(requestEntity);
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                String data = EntityUtils.toString(resEntity, "UTF-8");
                System.out.println(data);
            } else {
                System.out.println(EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    post请求json
     */
//    public static JSONObject post2(String url, String jsonString) {
//        HttpClient client = HttpClientBuilder.create().build();
//        HttpPost post = new HttpPost(url);
//        String data = null;
//        try {
//            StringEntity requestEntity = new StringEntity(jsonString, "UTF-8");
//            requestEntity.setContentEncoding("utf-8");
//            post.setHeader("Content-type", "application/json");
//            post.setEntity(requestEntity);
//            ;
//            HttpResponse response = client.execute(post);
//            HttpEntity resEntity = response.getEntity();
//            data = EntityUtils.toString(resEntity, "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return JSON.parseObject(data);
//    }

    public static JSONObject post2(String url, String jsonString) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject data = null;
        try {
            StringEntity requestEntity = new StringEntity(jsonString, "UTF-8");
            requestEntity.setContentEncoding("utf-8");
            post.setHeader("Content-type", "application/json");
            post.setEntity(requestEntity);
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                data = JSON.parseObject(EntityUtils.toString(resEntity, "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    /*
    post请求 formdata
     */
    public static JSONObject post3(String url, String text) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("text", text));
        JSONObject data = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                data = JSON.parseObject(EntityUtils.toString(resEntity, "utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
上一篇下一篇

猜你喜欢

热点阅读