精华内容
下载资源
问答
  • Java请求HTTP接口
    2021-10-19 16:49:06

    直接上代码

    代码示例是POST请求,如果GET就把参数换了就好了。

        /**
         * http请求获取数据
         *
         * @param url 请求的目标地址
         * @param data 要传递的参数,必须是JSONObject格式
         * @param token 如果请求的目前地址需要token就传,没有就传个null或""
         * @return
         */
        public static String httpURLConnectionPOST(String url, JSONObject data, String token) {
            StringBuffer strBf = new StringBuffer();
            try {
                URL realUrl = new URL(url);
                //将realUrl以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
                //此时cnnection只是为一个连接对象,待连接中
                HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
                //设置连接输出流为true,默认false (post请求是以流的方式隐式的传递参数)
                connection.setDoOutput(true);
                //设置连接输入流为true
                connection.setDoInput(true);
                //设置请求方式为post
                connection.setRequestMethod("POST");
                //post请求缓存设为false
                connection.setUseCaches(false);
                //设置该HttpURLConnection实例是否自动执行重定向
                connection.setInstanceFollowRedirects(true);
                //设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
                connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                if (StringUtils.isNotEmpty(token)) {
                    //设置token请求头信息
                    connection.setRequestProperty("Authorization", "Bearer " + token);
                }
                //建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
                connection.connect();
                //创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
                DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
                String query = data.toString();
                //将参数输出到连接
                dataout.write(query.getBytes("UTF-8"));
                // 输出完成后刷新并关闭流
                dataout.flush();
                dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    strBf.append(lines);
                }
                reader.close();
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return strBf.toString();
        }
    }
    

    请求成功后返回的是string字符串,需要把数据转成JSONObject,再取出数据走自己的业务。

    更多相关内容
  • 主要介绍了Java发送http get/post请求调用接口/方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • java通过HTTP调用接口Get请求和Post请求
  • JAVA 调用HTTP接口POST或GET实现方式,java通用
  • Java 发送Http get/post请求调用Http接口、方法

    Java 发送Http get/post请求

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

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

    URL包实现

    当前实现所需要的URL是在package java.net包下,点击查看源码,由此可知,此包是JDK自带的包!使用URL发送Http请求使用的是最原始方法发送!
    在这里插入图片描述

    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;
        }
    

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

    展开全文
  • 标题java调用HTTP接口Get请求和Post请求) package com.example.controller; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public ...

    标题java调用HTTP接口(Get请求和Post请求)

    package com.example.controller;
    
    import com.alibaba.fastjson.JSONObject;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class testMain {
        public static void main(String[] args) {
            String a = sendPost("http://localhost:8022/girl","{'name':'xiaohong','title':'heihei'}");//post 415可能是请求头的问题400可能是传的参数格式
            interfaceUtil("http://localhost:8022/girl?name=xiaohong&title=heihei","");//get
            System.out.println(a);
        }
        public static String sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");
                conn.setUseCaches(false);
                conn.setInstanceFollowRedirects(true);
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
                conn.connect();
    
                OutputStreamWriter outputStreamWriter =
                        new OutputStreamWriter(conn.getOutputStream(),"utf-8");
                out = new PrintWriter(outputStreamWriter);
                //转化json格式字符串
                JSONObject jsonObject = JSONObject.parseObject(param);
                out.print(jsonObject);
                // flush输出流的缓冲
                out.flush();
                out.close();
                //查看状态码
                int responseCode = conn.getResponseCode();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 调用对方接口方法
         * @param path 对方或第三方提供的路径
         * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
         */
        public static void interfaceUtil(String path,String data) {
            try {
                URL url = new URL(path);
                //打开和url之间的连接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                PrintWriter out = null;
    
                /**设置URLConnection的参数和普通的请求属性****start***/
    
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
    
                /**设置URLConnection的参数和普通的请求属性****end***/
    
                //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
                //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
                //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
                conn.setDoOutput(true);
                conn.setDoInput(true);
    
                conn.setRequestMethod("GET");//GET和POST必须全大写
                /**GET方法请求*****start*/
                /**
                 * 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
                 * 如果发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。
                 * */
                conn.connect();
    
                /**GET方法请求*****end*/
    
                /***POST方法请求****start*/
    
                /*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流
    
                out.print(data);//发送请求参数即数据
    
                out.flush();//缓冲数据
                */
                /***POST方法请求****end*/
    
                //获取URLConnection对象对应的输入流
                InputStream is = conn.getInputStream();
                //构造一个字符流缓存
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str = "";
                while ((str = br.readLine()) != null) {
                    str=new String(str.getBytes(),"UTF-8");//解决中文乱码问题
                    System.out.println(str);
                }
                //关闭流
                is.close();
                //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
                //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
                conn.disconnect();
                System.out.println("完整结束");
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    }
    
    
    展开全文
  • java代码-使用java解决http请求SOAP webService接口的源代码 ——学习参考资料:仅用于个人学习使用
  • Java 调用Http Rest接口 例子说明

    热门讨论 2016-07-07 21:50:21
    Java 调用Http Rest接口 例子说明
  • get请求,参数可以拼接在url上 post请求,参数使用json字符串 package org.example; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache....

    1.示例

    • get请求,参数可以拼接在url上
    • post请求,参数使用json字符串
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.10</version>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    
    package org.example;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.CharArrayBuffer;
    import org.apache.http.util.EntityUtils;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import java.util.stream.Collectors;
    
    public class TTest {
    	//get
        public static String getHttp(String url) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL urls = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                out = new PrintWriter(conn.getOutputStream());
                out.flush();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                result = in.lines().collect(Collectors.joining());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return result;
        }
        //get
        public static String getJson(String url) {
            String result = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet post = new HttpGet(url);
            CloseableHttpResponse response = null;
            try {
                post.setHeader("Content-Type", "application/json");
                response = httpClient.execute(post);
                if (response != null && response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    result = entityToString(entity);
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        //post
        public static String postJson(String url, String jsonString) {
            String result = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            CloseableHttpResponse response = null;
            try {
                post.setHeader("Content-Type", "application/json");
                if (null != jsonString) {
                    post.setEntity(new ByteArrayEntity(jsonString.getBytes(StandardCharsets.UTF_8)));
                }
                response = httpClient.execute(post);
                if (response != null && response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    result = entityToString(entity);
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        public static String entityToString(HttpEntity entity) throws IOException {
            String result = null;
            if (entity != null) {
                long length = entity.getContentLength();
                if (length != -1 && length < 2048) {
                    result = EntityUtils.toString(entity, "UTF-8");
                } else {
                    try (InputStreamReader reader1 = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)) {
                        CharArrayBuffer buffer = new CharArrayBuffer(2048);
                        char[] tmp = new char[1024];
                        int l;
                        while ((l = reader1.read(tmp)) != -1) {
                            buffer.append(tmp, 0, l);
                        }
                        result = buffer.toString();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    
        //POST请求以application/x-www-form-urlencoded;charset=utf-8格式
        public static String postForm(String postURL,String name,String age){
            PostMethod postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            //参数设置,需要注意的就是里边不能传NULL,要传空字符串
            NameValuePair[] data = {
                    new NameValuePair("name",name),
                    new NameValuePair("age",age)
            };
            postMethod.setRequestBody(data);
            HttpClient httpClient = new HttpClient();
            String result = null;
            try {
                httpClient.executeMethod(postMethod);
                result = postMethod.getResponseBodyAsString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
        public static void main(String[] args) {
            System.out.println(getHttp("https://www.baidu.com"));
            System.out.println("--------------------------------华丽的分割线-----------------------------------");
            System.out.println(postJson("https://www.baidu.com", null));
            System.out.println("--------------------------------华丽的分割线-----------------------------------");
            System.out.println(postForm("https://www.baidu.com", null, null));
        }
    }
    
    

    2.打印

    <!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
    --------------------------------华丽的分割线-----------------------------------
    <!DOCTYPE html>
    <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                    </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
    --------------------------------华丽的分割线-----------------------------------
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <style data-for="result" id="css_result">
    body{color:#333;background:#fff;padding:6px 0 0;margin:0;position:relative;min-width:900px}body,th,td,.p1,.p2{font-family:arial}p,form,ol,ul,li,dl,dt,dd,h3{margin:0;padding:0;list-style:none}input{padding-top:0;padding-bottom:0;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}table,img{border:0}td{font-size:9pt;line-height:18px}
    
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.util.*;
    
    public class TTest {
    
        //post params
        public static String postParams(String url, Map<String, String> params, Map<String, String> header) {
            String result = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost request = new HttpPost(url);
            CloseableHttpResponse response;
            try {
                if (params != null) {
                    UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(addParams(params), "UTF-8");
                    request.setEntity(uefEntity);
                }
                addHeader(header, request);
                response = httpClient.execute(request);
                if (response == null) {
                    return null;
                }
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    
        private static List<BasicNameValuePair> addParams(Map<String, String> map) {
            List<BasicNameValuePair> formParams = new ArrayList<>();
            if (map != null) {
                Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            return formParams;
        }
    
        private static void addHeader(Map<String, String> map, HttpPost post) {
            if (map != null) {
                Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    post.setHeader(entry.getKey(), entry.getValue());
                }
            }
        }
    
        public static void main(String[] args) {
            String url = "https://www.baidu.com";
            Map<String, String> para = new HashMap<>();
            Map<String, String> header = new HashMap<>();
            String s = postParams(url, para, header);
            System.out.println(s);
        }
    
    }
    
    展开全文
  • 本文通过实例代码给大家介绍了Java 发送http请求上传文件功能,需要的朋友参考下吧
  • 主要介绍了java后台调用HttpURLConnection类模拟浏览器请求实例,该实例可用于接口调用,具有一定的实用价值,需要的朋友可以参考下
  • 从Java到Python 通过http调用接口的方式实现java调用Python程序,进行数据交互
  • 使用GET方式1.2、发送带数据的请求,使用POST方法二、在应用A的Controller中调用http接口2.1 无数据传递2.2 有文件等数据传递三、应用B的Controller接收来自应用A的HTTP请求四、应用A接收应用B的返回结果。...
  • HttpUtils 工具类 ... import org.slf4j.Logger;...import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.spri
  • 主要介绍了java http token请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • java实现调用httpclient接口的类和方法,包括了get和post传参方式,简单易懂
  • http和WebService 调用接口Java代码demo,可配置根据情况自行配置内网访问
  • Java如何发起http请求 前言 一、GET与POST 1.GET方法 2.POST方法 实现代码 实例演示 字符串转json 结束 前言 在未来做项目中,一些功能模块可能会采用不同的语言...使用GET方法,需要传递的参数被附加在URL地址后面一起
  • 之前都是使用 ajax请求接口,现在记录一下使用 java请求接口的方法 使用 HttpURLConnection ... String methodUrl = "请求http接口地址"; HttpURLConnection connection = null; BufferedReader reade...
  • packagecom.vcgeek.hephaestus....importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.util.HashMap;importjava.util.List;importj...
  • Java接口调用方法 http请求get、post方法
  • 一. 简介HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。...用法使用HttpClient发送请求、...
  • 下面小编就为大家分享一篇java发起http请求获取返回的Json对象方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 1.java实现调用http请求的几种常见方式 (四种参考地址) 2.java调用http接口的几种方式总结 (三种方式参考地址) 2.1.HttpURLConnection (HttpURLConnection 参考地址) 2.1.1简介 2.1.2 GET方式调用 2.1.2 POST方式...
  • 网上的调用方法实例千奇百怪,以下为本人自己整理的Java调用rest接口方法实例,包含get请求和post请求,可创建工具类方便调用,其中post请求解决了入出参中文乱码问题。 get方式请求 //get方式请求 public ...
  • 使用java实现HTTPGET请求

    千次阅读 2020-05-12 11:33:03
    在前几节我们详细讲解了http协议的相关信息,基于“知行合一”的原则,只有通过具体动手实践才有可能检验知识点被我们真正掌握,本节我们就使用代码实现httpget请求。 首先需要一个http服务器,基于简单原则,我...
  • 主要介绍了java使用httpclient模拟post请求get请求示例,需要的朋友可以参考下

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,079,093
精华内容 431,637
关键字:

java调用http接口get请求

java 订阅