get请求实例 - CSDN
精华内容
参与话题
  • HttpClient Get请求实例

    千次阅读 2019-05-10 19:43:56
    Apache HttpComponents™项目负责创建和维护一个专注于HTTP和相关协议的低级Java组件工具集。该项目在Apache软件基金会下运行,并且是更大的开发人员和用户社区的一部分。 很多情况下我们都会用到HttpClient来发送G...

    Httpclient是我们平时中用的比较多的,但是一般用的时候都是去网上百度一下,把demo直接拿过来改一下用就行了,接下来我们来看他的一些具体的用法。Apache HttpComponents™项目负责创建和维护一个专注于HTTP和相关协议的低级Java组件工具集。该项目在Apache软件基金会下运行,并且是更大的开发人员和用户社区的一部分。

    很多情况下我们都会用到HttpClient来发送Get请求,下面我来看下具体的代码:

    CloseableHttpClient httpclient = HttpClients.createDefalt();
    HttpGet httpget = new HttpGet("http://www.baidu.com");
    
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50000).setSocketTimeout(50000)
    				.setConnectionRequestTimeout(3000).build();
    httpget.setConfig(requestConfig);
    CloseableHttpResponse response = httpClient.execute(httpget);
    if (response != null) {
    	HttpEntity entity = response.getEntity(); // 获取返回实体
    	if (entity != null) {
    	    EntityUtils.toString(entity)
    	}
    }

    这是CloseableHttpClient的源码可知:

    这个类继承自HttpClient,我们继续分析HttpClient类,可以看到他是顶级的接口类。

    HttpClients的一些工具类,我们来看:

    继续看build是个什么东西:

    public CloseableHttpClient build() {
            // Create main request executor
            // We copy the instance fields to avoid changing them, and rename to avoid accidental use of the wrong version
            PublicSuffixMatcher publicSuffixMatcherCopy = this.publicSuffixMatcher;
            if (publicSuffixMatcherCopy == null) {
                publicSuffixMatcherCopy = PublicSuffixMatcherLoader.getDefault();
            }
    
            HttpRequestExecutor requestExecCopy = this.requestExec;
            if (requestExecCopy == null) {
                requestExecCopy = new HttpRequestExecutor();
            }
            HttpClientConnectionManager connManagerCopy = this.connManager;
            if (connManagerCopy == null) {
                LayeredConnectionSocketFactory sslSocketFactoryCopy = this.sslSocketFactory;
                if (sslSocketFactoryCopy == null) {
                    final String[] supportedProtocols = systemProperties ? split(
                            System.getProperty("https.protocols")) : null;
                    final String[] supportedCipherSuites = systemProperties ? split(
                            System.getProperty("https.cipherSuites")) : null;
                    HostnameVerifier hostnameVerifierCopy = this.hostnameVerifier;
                    if (hostnameVerifierCopy == null) {
                        hostnameVerifierCopy = new DefaultHostnameVerifier(publicSuffixMatcherCopy);
                    }
                    if (sslContext != null) {
                        sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                sslContext, supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
                    } else {
                        if (systemProperties) {
                            sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                    (SSLSocketFactory) SSLSocketFactory.getDefault(),
                                    supportedProtocols, supportedCipherSuites, hostnameVerifierCopy);
                        } else {
                            sslSocketFactoryCopy = new SSLConnectionSocketFactory(
                                    SSLContexts.createDefault(),
                                    hostnameVerifierCopy);
                        }
                    }
                }
                @SuppressWarnings("resource")
                final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", sslSocketFactoryCopy)
                            .build(),
                        null,
                        null,
                        dnsResolver,
                        connTimeToLive,
                        connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS);
                if (defaultSocketConfig != null) {
                    poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
                }
                if (defaultConnectionConfig != null) {
                    poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
                }
                if (systemProperties) {
                    String s = System.getProperty("http.keepAlive", "true");
                    if ("true".equalsIgnoreCase(s)) {
                        s = System.getProperty("http.maxConnections", "5");
                        final int max = Integer.parseInt(s);
                        poolingmgr.setDefaultMaxPerRoute(max);
                        poolingmgr.setMaxTotal(2 * max);
                    }
                }
                if (maxConnTotal > 0) {
                    poolingmgr.setMaxTotal(maxConnTotal);
                }
                if (maxConnPerRoute > 0) {
                    poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
                }
                connManagerCopy = poolingmgr;
            }
            ConnectionReuseStrategy reuseStrategyCopy = this.reuseStrategy;
            if (reuseStrategyCopy == null) {
                if (systemProperties) {
                    final String s = System.getProperty("http.keepAlive", "true");
                    if ("true".equalsIgnoreCase(s)) {
                        reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
                    } else {
                        reuseStrategyCopy = NoConnectionReuseStrategy.INSTANCE;
                    }
                } else {
                    reuseStrategyCopy = DefaultClientConnectionReuseStrategy.INSTANCE;
                }
            }
            ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy;
            if (keepAliveStrategyCopy == null) {
                keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE;
            }
            AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy;
            if (targetAuthStrategyCopy == null) {
                targetAuthStrategyCopy = TargetAuthenticationStrategy.INSTANCE;
            }
            AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy;
            if (proxyAuthStrategyCopy == null) {
                proxyAuthStrategyCopy = ProxyAuthenticationStrategy.INSTANCE;
            }
            UserTokenHandler userTokenHandlerCopy = this.userTokenHandler;
            if (userTokenHandlerCopy == null) {
                if (!connectionStateDisabled) {
                    userTokenHandlerCopy = DefaultUserTokenHandler.INSTANCE;
                } else {
                    userTokenHandlerCopy = NoopUserTokenHandler.INSTANCE;
                }
            }
    
            String userAgentCopy = this.userAgent;
            if (userAgentCopy == null) {
                if (systemProperties) {
                    userAgentCopy = System.getProperty("http.agent");
                }
                if (userAgentCopy == null) {
                    userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient",
                            "org.apache.http.client", getClass());
                }
            }
    
            ClientExecChain execChain = createMainExec(
                    requestExecCopy,
                    connManagerCopy,
                    reuseStrategyCopy,
                    keepAliveStrategyCopy,
                    new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
                    targetAuthStrategyCopy,
                    proxyAuthStrategyCopy,
                    userTokenHandlerCopy);
    
            execChain = decorateMainExec(execChain);
    
            HttpProcessor httpprocessorCopy = this.httpprocessor;
            if (httpprocessorCopy == null) {
    
                final HttpProcessorBuilder b = HttpProcessorBuilder.create();
                if (requestFirst != null) {
                    for (final HttpRequestInterceptor i: requestFirst) {
                        b.addFirst(i);
                    }
                }
                if (responseFirst != null) {
                    for (final HttpResponseInterceptor i: responseFirst) {
                        b.addFirst(i);
                    }
                }
                b.addAll(
                        new RequestDefaultHeaders(defaultHeaders),
                        new RequestContent(),
                        new RequestTargetHost(),
                        new RequestClientConnControl(),
                        new RequestUserAgent(userAgentCopy),
                        new RequestExpectContinue());
                if (!cookieManagementDisabled) {
                    b.add(new RequestAddCookies());
                }
                if (!contentCompressionDisabled) {
                    if (contentDecoderMap != null) {
                        final List<String> encodings = new ArrayList<String>(contentDecoderMap.keySet());
                        Collections.sort(encodings);
                        b.add(new RequestAcceptEncoding(encodings));
                    } else {
                        b.add(new RequestAcceptEncoding());
                    }
                }
                if (!authCachingDisabled) {
                    b.add(new RequestAuthCache());
                }
                if (!cookieManagementDisabled) {
                    b.add(new ResponseProcessCookies());
                }
                if (!contentCompressionDisabled) {
                    if (contentDecoderMap != null) {
                        final RegistryBuilder<InputStreamFactory> b2 = RegistryBuilder.create();
                        for (final Map.Entry<String, InputStreamFactory> entry: contentDecoderMap.entrySet()) {
                            b2.register(entry.getKey(), entry.getValue());
                        }
                        b.add(new ResponseContentEncoding(b2.build()));
                    } else {
                        b.add(new ResponseContentEncoding());
                    }
                }
                if (requestLast != null) {
                    for (final HttpRequestInterceptor i: requestLast) {
                        b.addLast(i);
                    }
                }
                if (responseLast != null) {
                    for (final HttpResponseInterceptor i: responseLast) {
                        b.addLast(i);
                    }
                }
                httpprocessorCopy = b.build();
            }
            execChain = new ProtocolExec(execChain, httpprocessorCopy);
    
            execChain = decorateProtocolExec(execChain);
    
            // Add request retry executor, if not disabled
            if (!automaticRetriesDisabled) {
                HttpRequestRetryHandler retryHandlerCopy = this.retryHandler;
                if (retryHandlerCopy == null) {
                    retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE;
                }
                execChain = new RetryExec(execChain, retryHandlerCopy);
            }
    
            HttpRoutePlanner routePlannerCopy = this.routePlanner;
            if (routePlannerCopy == null) {
                SchemePortResolver schemePortResolverCopy = this.schemePortResolver;
                if (schemePortResolverCopy == null) {
                    schemePortResolverCopy = DefaultSchemePortResolver.INSTANCE;
                }
                if (proxy != null) {
                    routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy);
                } else if (systemProperties) {
                    routePlannerCopy = new SystemDefaultRoutePlanner(
                            schemePortResolverCopy, ProxySelector.getDefault());
                } else {
                    routePlannerCopy = new DefaultRoutePlanner(schemePortResolverCopy);
                }
            }
    
            // Optionally, add service unavailable retry executor
            final ServiceUnavailableRetryStrategy serviceUnavailStrategyCopy = this.serviceUnavailStrategy;
            if (serviceUnavailStrategyCopy != null) {
                execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategyCopy);
            }
    
            // Add redirect executor, if not disabled
            if (!redirectHandlingDisabled) {
                RedirectStrategy redirectStrategyCopy = this.redirectStrategy;
                if (redirectStrategyCopy == null) {
                    redirectStrategyCopy = DefaultRedirectStrategy.INSTANCE;
                }
                execChain = new RedirectExec(execChain, routePlannerCopy, redirectStrategyCopy);
            }
    
            // Optionally, add connection back-off executor
            if (this.backoffManager != null && this.connectionBackoffStrategy != null) {
                execChain = new BackoffStrategyExec(execChain, this.connectionBackoffStrategy, this.backoffManager);
            }
    
            Lookup<AuthSchemeProvider> authSchemeRegistryCopy = this.authSchemeRegistry;
            if (authSchemeRegistryCopy == null) {
                authSchemeRegistryCopy = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                    .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                    .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
                    .build();
            }
            Lookup<CookieSpecProvider> cookieSpecRegistryCopy = this.cookieSpecRegistry;
            if (cookieSpecRegistryCopy == null) {
                cookieSpecRegistryCopy = CookieSpecRegistries.createDefault(publicSuffixMatcherCopy);
            }
    
            CookieStore defaultCookieStore = this.cookieStore;
            if (defaultCookieStore == null) {
                defaultCookieStore = new BasicCookieStore();
            }
    
            CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;
            if (defaultCredentialsProvider == null) {
                if (systemProperties) {
                    defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
                } else {
                    defaultCredentialsProvider = new BasicCredentialsProvider();
                }
            }
    
            List<Closeable> closeablesCopy = closeables != null ? new ArrayList<Closeable>(closeables) : null;
            if (!this.connManagerShared) {
                if (closeablesCopy == null) {
                    closeablesCopy = new ArrayList<Closeable>(1);
                }
                final HttpClientConnectionManager cm = connManagerCopy;
    
                if (evictExpiredConnections || evictIdleConnections) {
                    final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm,
                            maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS);
                    closeablesCopy.add(new Closeable() {
    
                        @Override
                        public void close() throws IOException {
                            connectionEvictor.shutdown();
                        }
    
                    });
                    connectionEvictor.start();
                }
                closeablesCopy.add(new Closeable() {
    
                    @Override
                    public void close() throws IOException {
                        cm.shutdown();
                    }
    
                });
            }
    
            return new InternalHttpClient(
                    execChain,
                    connManagerCopy,
                    routePlannerCopy,
                    cookieSpecRegistryCopy,
                    authSchemeRegistryCopy,
                    defaultCookieStore,
                    defaultCredentialsProvider,
                    defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
                    closeablesCopy);
        }

    我们可以看到他这个的实现是非常复杂的,我们来看execute方法:

     

    他是一个抽象类,具体的实现在子类:

    @Override
        protected final CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request,
                                          final HttpContext context)
            throws IOException, ClientProtocolException {
    
            Args.notNull(request, "HTTP request");
            // a null target may be acceptable, this depends on the route planner
            // a null context is acceptable, default context created below
    
            HttpContext execContext = null;
            RequestDirector director = null;
            HttpRoutePlanner routePlanner = null;
            ConnectionBackoffStrategy connectionBackoffStrategy = null;
            BackoffManager backoffManager = null;
    
            // Initialize the request execution context making copies of
            // all shared objects that are potentially threading unsafe.
            synchronized (this) {
    
                final HttpContext defaultContext = createHttpContext();
                if (context == null) {
                    execContext = defaultContext;
                } else {
                    execContext = new DefaultedHttpContext(context, defaultContext);
                }
                final HttpParams params = determineParams(request);
                final RequestConfig config = HttpClientParamConfig.getRequestConfig(params);
                execContext.setAttribute(ClientContext.REQUEST_CONFIG, config);
    
                // Create a director for this request
                director = createClientRequestDirector(
                        getRequestExecutor(),
                        getConnectionManager(),
                        getConnectionReuseStrategy(),
                        getConnectionKeepAliveStrategy(),
                        getRoutePlanner(),
                        getProtocolProcessor(),
                        getHttpRequestRetryHandler(),
                        getRedirectStrategy(),
                        getTargetAuthenticationStrategy(),
                        getProxyAuthenticationStrategy(),
                        getUserTokenHandler(),
                        params);
                routePlanner = getRoutePlanner();
                connectionBackoffStrategy = getConnectionBackoffStrategy();
                backoffManager = getBackoffManager();
            }
    
            try {
                if (connectionBackoffStrategy != null && backoffManager != null) {
                    final HttpHost targetForRoute = (target != null) ? target
                            : (HttpHost) determineParams(request).getParameter(
                                    ClientPNames.DEFAULT_HOST);
                    final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);
    
                    final CloseableHttpResponse out;
                    try {
                        out = CloseableHttpResponseProxy.newProxy(
                                director.execute(target, request, execContext));
                    } catch (final RuntimeException re) {
                        if (connectionBackoffStrategy.shouldBackoff(re)) {
                            backoffManager.backOff(route);
                        }
                        throw re;
                    } catch (final Exception e) {
                        if (connectionBackoffStrategy.shouldBackoff(e)) {
                            backoffManager.backOff(route);
                        }
                        if (e instanceof HttpException) {
                            throw (HttpException)e;
                        }
                        if (e instanceof IOException) {
                            throw (IOException)e;
                        }
                        throw new UndeclaredThrowableException(e);
                    }
                    if (connectionBackoffStrategy.shouldBackoff(out)) {
                        backoffManager.backOff(route);
                    } else {
                        backoffManager.probe(route);
                    }
                    return out;
                } else {
                    return CloseableHttpResponseProxy.newProxy(
                            director.execute(target, request, execContext));
                }
            } catch(final HttpException httpException) {
                throw new ClientProtocolException(httpException);
            }
        }

    这个是他里边的一个实现,可以看出来,也是非常复杂的。HttpClient Get的请求大概就这么多,想深入的同学可以去仔细研究源码。

    有问题可以在下面评论,技术问题可以私聊我。

    展开全文
  • $.ajax GET请求案例

    千次阅读 2019-06-22 13:39:31
    前端JS代码: $.ajax({ type: "GET", url: getRootPath() + "/getDatas.do", contentType: 'application/json;charset=utf-8', //设置请求头信息 data: "devId=" + devId, //必...

    前端JS代码:

     $.ajax({
                type: "GET",
                url: getRootPath() + "/getDatas.do",
                contentType: 'application/json;charset=utf-8', //设置请求头信息
                data: "devId=" + devId, //必须是字符串
                dataType: "json",
                success: function (res) {
                    if (res.rtnCode == 0) {
                        successToast(res.msg);
                    }
                },
                error: function (result) {
                    errorToast(result.msg);
                }
            });
    

    后端代码:

        @RequestMapping(value = "/getDatas.do", method = RequestMethod.GET)
        @ResponseBody
        public Result getDatas(HttpServletRequest request) {
            Result result = new Result();
            String devId= request.getParameter("devId");
            result.setMsg("查询成功:" + devId);
            return result;
        }
    
    展开全文
  • HTTP get post 请求实例

    2019-06-30 01:35:18
    package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection;.....
    package wzh.Http;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.List;
    import java.util.Map;
    
    public class HttpRequest {
        /**
         * 向指定URL发送GET方法的请求
         * 
         * @param url
         *            发送请求的URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @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();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 向指定 URL 发送POST方法的请求
         * 
         * @param url
         *            发送请求的 URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static 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);
                // 获取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) {
                    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;
        }    
    }
    
    
    public static void main(String[] args) {
            //发送 GET 请求
            String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
            System.out.println(s);
            
            //发送 POST 请求
            String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
            System.out.println(sr);
        }

     

    转载于:https://www.cnblogs.com/diandianquanquan/p/10606984.html

    展开全文
  • HTTP请求详解含POST,GET实例

    万次阅读 多人点赞 2018-05-05 21:45:55
    前言单纯的copy代码没有用,本篇从http请求的基本原理开始为大家讲解,后边有实例,希望大家一步一步看完,这样无论编写什么请求我们都可以得心应手。HTTP的组成http消息由客户端到服务端的请求以及服务端到客户端的...

    前言

    单纯的copy代码没有用,本篇从http请求的基本原理开始为大家讲解,后边有实例,希望大家一步一步看完,这样无论编写什么请求我们都可以得心应手。

    HTTP的组成

    http消息由客户端到服务端的请求以及服务端到客户端的响应组成

    HTTP请求报文的格式

    请求头与请求正文中间有一行空行,是告诉服务器请求头到此结束了接下来是请求正文

    请求方法:get,post,head,delete等等,告诉服务器你的具体操作是什么

    URL:可以从互联网上得到资源的位置和访问方法的一种简洁标识。URL结构:协议://域名 or IP地址:端口号/目录/文件名.文件名后缀?参数=值
    协议版本:目前几乎用的都是http1.1版本,增加了一个很重要的特性它支持长连接,其他具体细微差别不做讲述。
    请求头:请求头部为请求报文添加了一些附加信息,由“名/值”对组成,每行一对,名和值之间使用冒号分隔。
    常用的请求头包括:

    请求正文:添加请求实体即你具体要请求的内容用于POST请求,GET不用

    HTTP响应报文格式


    HTTP状态码


    HTTP响应头


    解析

    通过上述分析,我们可以发现HTTP请求其实像发送邮件一样,我们告诉邮局地址,邮局发送邮件,请求头是我们附加的一些信息,可以告诉收件人,谁发的邮件,谁可以看

    ,这是一封加密的邮件,你要根据什么规则把这封邮件翻译过来等等规则,请求内容当然就是我们要发送的具体内容,响应就是收件人给我的回信,响应头会告诉我们一些附加信息比如他告诉我们,你发送的那个收件人没有(404)或者我正确收到了你的来信(200),我给你的响应是什么加密方式,你要怎么解码,响应内容就是他要告诉我们的具体内容,你也可以把邮局当做一个代理,收件人当做服务器。

    实战

    接下来,我们根据以上规则使用JAVA来构造一些请求

    POST不带请求实体请求方法

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.client.utils.URIBuilder;
    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.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class TestHttp{
    	public void postOne(){
    		HttpClient client = new DefaultHttpClient();
    		HttpResponse response = null;
    		String url = "http://write.blog.csdn.net/postedit";
    		HttpPost post = new HttpPost(url);
    		post.setHeader("Content-Type", "application/json");
    		response = client.execute(post);
    		String	ret      = EntityUtils.toString(response.getEntity(),"UTF-8");
    		System.out.println(ret);
    }
    }
    解析:
    1,首先我们要构造一个客户端,apache对HttpClient这个类的解释是该接口仅表示HTTP请求执行的最基本合同,它不会对请求执行过程施加任何限制或具体细节,并且将状态管理,身份验证和重定向处理的细节留给个别实现。具体意思就是我们要发送HTTP请求就要先构造这个HTTPClient,但是涉及一些具体的细节比如cookies,header,request   body我们不需要用它来实现,这些具体的细节我们留给其他类来实现,
    2,我们构造一个请求地址,即我们要把这个请求发送给谁
    3,构建Post请求,HttpPost有一个构造器HttpPost(String uri) ,我们用这个构造器来初始化HttpPost
    4,添加header,HttpPost里有一个setheader和addheader方法,这些方法是它继承接口org.apache.http.HttpMessage得来的,这里说一下add和set的区别,首先同名header
    可以有多个,运行时使用第一个,当我们使用addheader时,如果同名header已经存在它会追加至原同名header后面,使用setheader时,他会覆盖同名的header,我在header
    中设定了我要发送的请求体是json形式的(实际上并未携带请求体,携带请求体的会在下边给例子)
    5,当我们构造好客户端,请求header,url地址后,此时就可以发送了,自然就是client.execute即执行这个请求
    6,接下来是接受响应,即我们发送完邮件后,别人给我们回信了,我们要设法获得这个回信的内容即HttpResponse response = client.execute(post) 来关联我们的请求和响应,意思就是这个响应是我执行这个请求的响应getEntity是这个类自带的方法,用来获取响应实体,即具体的响应内容,它还有很多方法,获取响应信息,感兴趣可以自行研究
    7,EntityUtils这个类主要是用来处理HttpEntity的,它有一些静态方法,我用的就是将这个响应实体以UTF-8的编码格式转换成字符串,最后打印出来

    具体响应

    <html><head><title>Object moved</title></head><body><h2>Object moved to <a href="https://passport.csdn.net/account/login?from=http%3a%2f%2fwrite.blog.csdn.net%2fpostedit">here</a>.</h2></body></html>
    解析:
    还有一些其他的内容,不在这里粘贴,返回的html代码是一个重新登录的地址链接,点击以后告诉我们重新登录,因为我访问的url是csdn的编辑页,不登录怎么可能直接访问呢,我们可以尝试使用cookie这里告诉大家一个进阶技巧,我们打开浏览器,启用开发者模式,然后重新登录一次,找到csdnbi这个接口,然后获取requestheader中的cookies
    具体如图:

    在这里找到cookie后我们使用post.setheader("Cookie","*****")就可越过登录,直接请求到这个页面了。感兴趣的可以试一下。

    具体响应

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <script type="text/javascript" src="//static-blog.csdn.net/scripts/tingyun-rum.js"></script><title>编辑文章 - CSDN博客</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <link type="text/css" rel="Stylesheet" href="http://c.csdnimg.cn/pig/blog/write/css/main.css" />    <!--new top-->        <link rel="stylesheet" href="http://c.csdnimg.cn/public/common/toolbar/css/index.css">     <!--new top-->       <script type="text/javascript" src="//static-blog.csdn.net/scripts/jquery.js"></script>    <script type="text/javascript" src="//static-blog.csdn.net/scripts/jquery-version.js"></script><script type="text/javascript" src="//static-blog.csdn.net/scripts/csdn.js"></script><script type="text/javascript" src="http://c.csdnimg.cn/pig/blog/write/scripts/master.js"></script>        <script type="text/javascript">var statichost = "//static-blog.csdn.net";</script>               <link type='text/css' rel='Stylesheet' href='http://c.csdnimg.cn/pig/blog/write/css/write.css' /><script type='text/javascript' src='http://c.csdnimg.cn/pig/blog/write/scripts/jquery.autocomplete.min.js'></script> <script type='text/javascript' src='//static-blog.csdn.net/xheditor/xheditor-1.1.13-zh-cn.js'></script><link type='text/css' rel='Stylesheet' href='http://c.csdnimg.cn/pig/blog/write/css/jquery.autocomplete.css' /></head><body></body></html>
    body里包含我的个人信息在这里就不给大家展示了

    POST带请求参数和请求实体

    前言:如果我们前边的都掌握了,那么接下来的就很容易理解了,我们知道post请求时会携带一些参数比如 http://www.123.com/index.html?a=123还有一些我们要发送的报文
    其实参数和报文的处理方式是一样的,那么我们只要构造这个请求实体不就可以了吗?
    		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    		nvps.add(new BasicNameValuePair("baowen","UTF-8"));
    		post.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));

    解析:
    1,我们加入BasicNameValuePair,这个类是干嘛用的呢,apache的官方解释是用作HTTP消息元素的名称 - 值对参数。我们就用它来构造参数
    2,我为什么用list,因为有时你的参数可能不止一个,这是它的一个构造器BasicNameValuePair(String name, String value) ,报文一定要是字符串格式,UrlEncodedForm
      Entity(List<? extends NameValuePair> parameters, String charset) 我要用这个类来构造实体就必须使用list来添加参数,同时这个类实际上是继承StringEntity,它又实现了
    HttpEntity这个接口,知道这一点很重要。
    3,public void setEntity(HttpEntity entity)这个方法要传入一个HttpEntity类型的参数,所以后边我可以直接用。

    GET不带参数请求

    		HttpGet get = new HttpGet(url);
    		get.setHeader("Content-Type", "application/json");
    		HttpResponse rese = client.execute(get);
    		String redsa = EntityUtils.toString(rese.getEntity());

    GET携带参数请求

    		 CloseableHttpClient client3 = HttpClients.createDefault();
    		 List<NameValuePair> nvps2 = new ArrayList<NameValuePair>();
    		 nvps2.add(new BasicNameValuePair("baowen","213"));
    		 HttpResponse resep = null;
    		 URIBuilder builder = new URIBuilder(url);
    		 builder.setParameters(nvps2);
    		 HttpGet get21312 = new HttpGet(builder.build());
    		 response = client.execute(get21312);
    		 String sdf = EntityUtils.toString(response.getEntity(),"UTF-8");

    注意

    1,后边的代码我没有写完整,我们需要根据自己的需求添加URL
    2,header里我用的都是json,大家可以根据自己需要什么类型做改变
    3,我将返回都转换成了字符串,方便打印
    4,我这里使用的是apache的http包,关于网络编程,JAVA也有自带的java.net包

    总结

    通过上边的学习我们明白,只要我们掌握了http请求由什么组成,哪些类来构造这些东西,然后在解析响应剩下的就对我们来说很简单了。万变不离其宗,这次我发这个总结主要是由于之前发的一遍http 发送 post请求 的贴访问量很高,感觉有必要指引一下新入坑的同学们,当然我自己也在学习之中,欢迎大家留言,咱们互相探讨,共同进步












    展开全文
  • 写的一个简单的vue get请求 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试get实例(runoob.com)</title> <script src=...
  • 举例对国家气象局接口自动化测试进行讲解(Get请求及结果断言),以达到自动化测试入门目的。
  • axios模拟GET请求实例及详解

    千次阅读 2018-07-31 10:54:28
    1、在my-project项目中引入axios依赖:cnpm install --save... // 在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $http命令 import axios from 'axios' Vue.prototype.$http = axios (将...
  • HTTP-XMLHttpRequest

    千次阅读 2020-07-14 11:07:42
    创建 XMLHttpRequest 实例 发出 Http 请求 接收服务器传回的数据 更新网页数据 XMLHttpRequest 实例属性 readyState:返回一个整数,表示实例对象的当前状态 0,表示 XMLHttpRequest 实例已经生成,但实例的 open() ...
  • Ajax get请求示例

    万次阅读 2019-07-03 08:27:39
    正好早上有时间,代码: $.ajax({ type:'GET', url:'proinfo', data:data, success:function(result){ //返回成功进行响应操作 //把获取信息填...
  • Springboot的POST、GET、PUT、DELETE请求实例

    万次阅读 多人点赞 2017-11-14 16:29:47
    Springboot的POST、GET、PUT、DELETE请求实例Springboot的POSTGETPUTDELETE请求实例
  • 详解HTTP GET请求

    千次阅读 2019-12-17 11:55:40
    实例1:NodeMcu通过TCP实现HTTP GET请求(无请求主体)srv = net.createConnection(net.TCP, 0) srv:on("receive", function(sck, c) print(c) end) srv:connect(80,"fanyi.youdao.com") srv:on("connection", ...
  • 单例模式使用httpclient发送请求

    千次阅读 2018-03-01 17:10:07
    使用httpclient发送post和get请求时,需要实例化HttpClient实例,再调用httpClient.execute()方法,每次实例化HttpClient耗时较大,而且HttpClient实例不能共用,不利于大量的请求处理,考虑到HttpClient实例公用,...
  • HttpClient设置请求头模拟浏览器

    万次阅读 2017-07-12 20:27:18
    之前的HelloWorld 爬虫一些特殊网站  package ... import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGe
  • Scala 通过HttpClients发送get和post请求

    千次阅读 2020-07-23 20:05:02
    Scala 通过HttpClients发送get和post请求 由于之前的工程代码都是使用Scala开发的,而最近工作中涉及到一个新功能需要发送post请求后端接口,今把如何使用HttpClients做个笔记。 get请求 def getResponse(url: ...
  • JSP/Servlet 工作原理(转载)

    万次阅读 多人点赞 2014-03-08 23:32:54
    Servlet Servlet 没有 main 方法,不能够独立的运行,它的运行需要容器的支持,Tomcat 是最常用...对于用户到达Servlet的请求,Servlet容器会创建特定于这个请求的ServletRequest对象和ServletResponse对象,然后调用S
  • 请求第一次调用负载均衡,实例列表是:[实例1,实例2],position为1,对2取余=1,所以请求发送到实例2上面了 请求失败,触发重试,实例列表缓存失效,更新后变成了:[实例2,实例1],position为2,对2取余=0,所以...
  • 本文演示用Postman做接口测试的实例。测试https://www.apishop.net中的“全国天气预报”的接口。 1.全国天气预报 1.1基本信息 接口地址:https://api.apishop.net/common/weather/get15DaysWeatherByArea 请求...
  • 超详细axios教程

    千次阅读 2020-06-03 15:32:21
    1 执行GET请求 2 执行POST请求 3 执行多个并发请求 axios API 1 axiosconfig 2 axiosurl config 3 请求方法别名 4 并发 5 创建实例 6 实例方法 请求配置 配置默认值 1 全局axios默认值 2 自定义实例...
  • postman发送get\post请求

    千次阅读 2017-09-24 08:59:29
    之前给大家介绍了postman安装和使用,下面给大家介绍一下get和post请求调用方式。 首先get和post请求的区别是什么呢,简单说一下: Get是向服务器发索取数据的一种...下面做一个get请求实例 如图显示的就是一个
  • Java模拟httpGet请求并获取返回的数据

    千次阅读 2017-11-02 16:49:21
    1.代码实例如下: public class HttpgetUtils { public static String sendGETRequest(String path, Map params, String ecoding) throws Exception{ //拼接GET参数条件 StringBuilder url = new ...
1 2 3 4 5 ... 20
收藏数 661,661
精华内容 264,664
热门标签
关键字:

get请求实例