Java 发送Http get/post请求,调用Http接口、方法

Java 发送Http get/post请求,调用Http接口、方法

  • Java 发送Http get/post请求
    • URL包实现
      • POST请求
      • GET请求
    • httpclient包实现
      • POST请求
      • GET请求

Java 发送Http get/post请求

本篇文章主要通过以下俩种包实现get/post请求方法!

  1. java.net.URL
  2. org.apache.http.client

URL包实现

当前实现所需要的URL是在package java.net包下,点击查看源码,由此可知,此包是JDK自带的包!使用URL发送Http请求使用的是最原始方法发送!
Java 发送Http get/post请求,调用Http接口、方法_第1张图片

POST请求

废话不多说,直接上代码,如下所示:

/**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL  (可以将参数丢url后面传过去URL?productCode=YUNPHMIP)
     * @param param
     *            请求参数,请求参数应该是json的形式。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置编码格式
            conn.setRequestProperty("Charset","UTF-8");
            conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            // 获取URLConnection对象对应的输出流
             out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
             out.print(param);
            // flush输出流的缓冲
          	 out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch( IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

若发送过程中存在乱码,解决办法如下所示:

       // 获取URLConnection对象对应的输出流
      OutputStream os = conn.getOutputStream();
      OutputStreamWriter ow = new OutputStreamWriter(os, "UTF-8");
      out = new PrintWriter(ow);
      // 发送请求参数
      out.print(param);
      // flush输出流的缓冲
      out.flush();

GET请求

具体代码如下所示:

/**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *   发送请求的URL
     * @param param
     *   请求参数,请求参数应该是 name=value&name1=value1 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

httpclient包实现

使用此方法实现需要引入pom文件,具体引入文件如下所示:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.8</version>
</dependency>

POST请求

具体代码如下所示:

	private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

   /**
     * get请求
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

GET请求

具体代码如下所示:

	private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

   /**
     * post请求
     * @param url
     * @param jsonString
     * @return
     */
    public static String post(String url, String jsonString) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            response =  httpClient.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

以上就是俩种不同包的连接方法!若有不足之处,请您指正!

你可能感兴趣的:(Spring,java,spring,struts,hibernate,maven)