• Java发送Http请求


    原文地址:Java发送Http请求

    1、方法一,通过apache的httpclient

    复制代码
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    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.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    import org.junit.Test;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class HttpTest {
        String uri = "http://127.0.0.1:8080/simpleweb";
    
        /**
         * Get方法
         */
        @Test
        public void test1() {
            try {
                CloseableHttpClient client = null;
                CloseableHttpResponse response = null;
                try {
                    HttpGet httpGet = new HttpGet(uri + "/test1?code=001&name=测试");
    
                    client = HttpClients.createDefault();
                    response = client.execute(httpGet);
                    HttpEntity entity = response.getEntity();
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                } finally {
                    if (response != null) {
                        response.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Post发送form表单数据
         */
        @Test
        public void test2() {
            try {
                CloseableHttpClient client = null;
                CloseableHttpResponse response = null;
                try {
                    // 创建一个提交数据的容器
                    List<BasicNameValuePair> parames = new ArrayList<>();
                    parames.add(new BasicNameValuePair("code", "001"));
                    parames.add(new BasicNameValuePair("name", "测试"));
    
                    HttpPost httpPost = new HttpPost(uri + "/test1");
                    httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
    
                    client = HttpClients.createDefault();
                    response = client.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                } finally {
                    if (response != null) {
                        response.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Post发送json数据
         */
        @Test
        public void test3() {
            try {
                CloseableHttpClient client = null;
                CloseableHttpResponse response = null;
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("code", "001");
                    data.put("name", "测试");
    
                    HttpPost httpPost = new HttpPost(uri + "/test2");
                    httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                    httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data),
                            ContentType.create("text/json", "UTF-8")));
    
                    client = HttpClients.createDefault();
                    response = client.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                } finally {
                    if (response != null) {
                        response.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    复制代码

     2、方法二,通过JDK自带的HttpURLConnection

    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.junit.Test;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class HttpApi {
        String uri = "http://127.0.0.1:7080/simpleweb";
    
        /**
         * Get方法
         */
        @Test
        public void test1() {
            try {
                URL url = new URL(uri + "/test1?code=001&name=测试");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
                connection.setDoOutput(true); // 设置该连接是可以输出的
                connection.setRequestMethod("GET"); // 设置请求方式
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = br.readLine()) != null) { // 读取数据
                    result.append(line + "
    ");
                }
                connection.disconnect();
    
                System.out.println(result.toString());//请求返回的数据,不会取的可以看我上一篇,java取json数据
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Post方法发送form表单
         */
        @Test
        public void test2() {
            try {
                URL url = new URL(uri + "/test1");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
                connection.setDoInput(true); // 设置可输入
                connection.setDoOutput(true); // 设置该连接是可以输出的
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
                pw.write("code=001&name=测试");
                pw.flush();
                pw.close();
    
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = br.readLine()) != null) { // 读取数据
                    result.append(line + "
    ");
                }
                connection.disconnect();
    
                System.out.println(result.toString());//请求返回的数据,不会取的可以看我上一篇,java取json数据
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Post方法发送json数据
         */
        @Test
        public void test3() {
            try {
                URL url = new URL(uri + "/test2");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
                connection.setDoInput(true); // 设置可输入
                connection.setDoOutput(true); // 设置该连接是可以输出的
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("code", "001");
                data.put("name", "测试");
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
                pw.write(objectMapper.writeValueAsString(data));
                pw.flush();
                pw.close();
    
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = br.readLine()) != null) { // 读取数据
                    result.append(line + "
    ");
                }
                connection.disconnect();
    
                System.out.println(result.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    3.   2020.08.19

     url是带着参数拼接好的。例如:sendHttpGet(StaticCode.CautionUrl+"?deviceId="+deviceId)

    token:选填的Header参数。

    /**
         * Http Get请求
         * @param url
         * @param token
         * @return
         * @throws Exception
         */
        public static String sendHttpGet(String url, String token) throws Exception {
               HttpClient httpClient;
               HttpGet postMethod;
               HttpResponse response;
               String reponseContent;
               httpClient = HttpClients.createDefault();
               postMethod = new HttpGet(url);
               postMethod.addHeader("Content-type", "application/json;charset=UTF-8");
               postMethod.addHeader("t-access-token", token);
               response = httpClient.execute(postMethod);
               HttpEntity httpEntity = response.getEntity();
               reponseContent = EntityUtils.toString(httpEntity);
               EntityUtils.consume(httpEntity);
               return reponseContent;
    
        }
    JSONBody:拼接的json参数,比如String JSONBody = "{"appKey":""+StaticCode.appKey+"","appSecret":""+StaticCode.appSecret+""}";
    /**
         * 发送http post请求
         *
         * @Create: 2020/8/19 13:58
         */
        public static String sendHttpPost(String url, String JSONBody) throws Exception {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
            httpPost.setEntity(new StringEntity(JSONBody));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //System.out.println(response.getStatusLine().getStatusCode() + "
    ");
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            response.close();
            httpClient.close();
            return responseContent;
        }
  • 相关阅读:
    QT生成流水账号
    Qt实现端口扫描器
    Qtablevies获取内容
    Qt中暂停线程的执行
    Qt经典出错信息之undefined reference to `vtable for classname
    Qt中 QString 和int, char等的“相互”转换
    caffe实现自己的层
    获取minist数据并转换成lmdb
    命名空间下接类,比如common.cpp
    caffe这个c++工程的目录结构
  • 原文地址:https://www.cnblogs.com/wl1202/p/13491251.html
Copyright © 2020-2023  润新知