Maison > Java > javaDidacticiel > le corps du texte

org.apache.httpcomponents:classe d'utilitaire httpclient

PHP中文网
Libérer: 2017-06-19 10:19:01
original
1799 Les gens l'ont consulté

Basé sur httpclient version 4.4.1

Étant donné que les connexions http nécessitent trois poignées de main, des ressources et du temps sont perdus lorsque des appels fréquents sont nécessaires

Utilisez donc le pool de connexions pour vous connecter

Modifier en fonction des besoins réels Le nombre maximum de connexions dans le pool de connexions et le nombre maximum de connexions dans le routage

 Une autre chose à noter est

   // 释放Socket流
     response.close();
     // 释放Connection
     // httpClient.close();<br><br>
Copier après la connexion
<span style="color: #008080">  1</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.HttpEntity;
</span><span style="color: #008080">  2</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.NameValuePair;
</span><span style="color: #008080">  3</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.config.RequestConfig;
</span><span style="color: #008080">  4</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.entity.UrlEncodedFormEntity;
</span><span style="color: #008080">  5</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.methods.CloseableHttpResponse;
</span><span style="color: #008080">  6</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.methods.HttpGet;
</span><span style="color: #008080">  7</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.methods.HttpPost;
</span><span style="color: #008080">  8</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.methods.HttpRequestBase;
</span><span style="color: #008080">  9</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.client.utils.URIBuilder;
</span><span style="color: #008080"> 10</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.config.SocketConfig;
</span><span style="color: #008080"> 11</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.entity.StringEntity;
</span><span style="color: #008080"> 12</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.impl.client.CloseableHttpClient;
</span><span style="color: #008080"> 13</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.impl.client.HttpClients;
</span><span style="color: #008080"> 14</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
</span><span style="color: #008080"> 15</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.message.BasicNameValuePair;
</span><span style="color: #008080"> 16</span> <span style="color: #0000ff">import</span><span style="color: #000000"> org.apache.http.util.EntityUtils;
</span><span style="color: #008080"> 17</span> 
<span style="color: #008080"> 18</span> <span style="color: #0000ff">import</span><span style="color: #000000"> java.io.IOException;
</span><span style="color: #008080"> 19</span> <span style="color: #0000ff">import</span><span style="color: #000000"> java.io.UnsupportedEncodingException;
</span><span style="color: #008080"> 20</span> <span style="color: #0000ff">import</span><span style="color: #000000"> java.net.URISyntaxException;
</span><span style="color: #008080"> 21</span> <span style="color: #0000ff">import</span><span style="color: #000000"> java.util.ArrayList;
</span><span style="color: #008080"> 22</span> <span style="color: #0000ff">import</span><span style="color: #000000"> java.util.Map;
</span><span style="color: #008080"> 23</span> 
<span style="color: #008080"> 24</span> <span style="color: #008000">/**</span>
<span style="color: #008080"> 25</span> <span style="color: #008000"> * Created by lidada on 2017/6/9.
</span><span style="color: #008080"> 26</span>  <span style="color: #008000">*/</span>
<span style="color: #008080"> 27</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span><span style="color: #000000"> HttpClientUtils {
</span><span style="color: #008080"> 28</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span><span style="color: #000000"> PoolingHttpClientConnectionManager cm;
</span><span style="color: #008080"> 29</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String EMPTY_STR = ""<span style="color: #000000">;
</span><span style="color: #008080"> 30</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String CONTENT_TYPE_UTF_8 = "UTF-8"<span style="color: #000000">;
</span><span style="color: #008080"> 31</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String CONTENT_TYPE_GBK = "GBK"<span style="color: #000000">;
</span><span style="color: #008080"> 32</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String CONTENT_TYPE_JSON = "application/json"<span style="color: #000000">;
</span><span style="color: #008080"> 33</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> <span style="color: #0000ff">int</span> CONNECTION_TIMEOUT_MS = 60000<span style="color: #000000">;
</span><span style="color: #008080"> 34</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> <span style="color: #0000ff">int</span> SO_TIMEOUT_MS = 60000<span style="color: #000000">;
</span><span style="color: #008080"> 35</span> 
<span style="color: #008080"> 36</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span><span style="color: #000000"> init() {
</span><span style="color: #008080"> 37</span>         <span style="color: #0000ff">if</span> (cm == <span style="color: #0000ff">null</span><span style="color: #000000">) {
</span><span style="color: #008080"> 38</span>             cm = <span style="color: #0000ff">new</span><span style="color: #000000"> PoolingHttpClientConnectionManager();
</span><span style="color: #008080"> 39</span>             cm.setMaxTotal(50);<span style="color: #008000">//</span><span style="color: #008000"> 整个连接池最大连接数</span>
<span style="color: #008080"> 40</span>             cm.setDefaultMaxPerRoute(5);<span style="color: #008000">//</span><span style="color: #008000"> 每路由最大连接数,默认值是2</span>
<span style="color: #008080"> 41</span>             SocketConfig sc =<span style="color: #000000"> SocketConfig.custom().setSoTimeout(SO_TIMEOUT_MS).build();
</span><span style="color: #008080"> 42</span> <span style="color: #000000">            cm.setDefaultSocketConfig(sc);
</span><span style="color: #008080"> 43</span> <span style="color: #000000">        }
</span><span style="color: #008080"> 44</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 45</span> 
<span style="color: #008080"> 46</span>     <span style="color: #008000">/**</span>
<span style="color: #008080"> 47</span> <span style="color: #008000">     * 通过连接池获取HttpClient
</span><span style="color: #008080"> 48</span> <span style="color: #008000">     *
</span><span style="color: #008080"> 49</span> <span style="color: #008000">     * </span><span style="color: #808080">@return</span>
<span style="color: #008080"> 50</span>      <span style="color: #008000">*/</span>
<span style="color: #008080"> 51</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span><span style="color: #000000"> CloseableHttpClient getHttpClient() {
</span><span style="color: #008080"> 52</span> <span style="color: #000000">        init();
</span><span style="color: #008080"> 53</span>         <span style="color: #0000ff">return</span> HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(<span style="color: #0000ff">true</span><span style="color: #000000">) .build();
</span><span style="color: #008080"> 54</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 55</span> 
<span style="color: #008080"> 56</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span><span style="color: #000000"> String httpGetRequest(String url) {
</span><span style="color: #008080"> 57</span>         HttpGet httpGet = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpGet(url);
</span><span style="color: #008080"> 58</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpGet);
</span><span style="color: #008080"> 59</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 60</span> 
<span style="color: #008080"> 61</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String httpGetRequest(String url, Map<String, Object> params) <span style="color: #0000ff">throws</span><span style="color: #000000"> URISyntaxException {
</span><span style="color: #008080"> 62</span>         URIBuilder ub = <span style="color: #0000ff">new</span><span style="color: #000000"> URIBuilder();
</span><span style="color: #008080"> 63</span> <span style="color: #000000">        ub.setPath(url);
</span><span style="color: #008080"> 64</span> 
<span style="color: #008080"> 65</span>         ArrayList<NameValuePair> pairs =<span style="color: #000000"> covertParams2NVPS(params);
</span><span style="color: #008080"> 66</span> <span style="color: #000000">        ub.setParameters(pairs);
</span><span style="color: #008080"> 67</span> 
<span style="color: #008080"> 68</span>         HttpGet httpGet = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpGet(ub.build());
</span><span style="color: #008080"> 69</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpGet);
</span><span style="color: #008080"> 70</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 71</span> 
<span style="color: #008080"> 72</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object><span style="color: #000000"> params)
</span><span style="color: #008080"> 73</span>             <span style="color: #0000ff">throws</span><span style="color: #000000"> URISyntaxException {
</span><span style="color: #008080"> 74</span>         URIBuilder ub = <span style="color: #0000ff">new</span><span style="color: #000000"> URIBuilder();
</span><span style="color: #008080"> 75</span> <span style="color: #000000">        ub.setPath(url);
</span><span style="color: #008080"> 76</span> 
<span style="color: #008080"> 77</span>         ArrayList<NameValuePair> pairs =<span style="color: #000000"> covertParams2NVPS(params);
</span><span style="color: #008080"> 78</span> <span style="color: #000000">        ub.setParameters(pairs);
</span><span style="color: #008080"> 79</span> 
<span style="color: #008080"> 80</span>         HttpGet httpGet = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpGet(ub.build());
</span><span style="color: #008080"> 81</span>         <span style="color: #0000ff">for</span> (Map.Entry<String, Object><span style="color: #000000"> param : headers.entrySet()) {
</span><span style="color: #008080"> 82</span> <span style="color: #000000">            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
</span><span style="color: #008080"> 83</span> <span style="color: #000000">        }
</span><span style="color: #008080"> 84</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpGet);
</span><span style="color: #008080"> 85</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 86</span> 
<span style="color: #008080"> 87</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span><span style="color: #000000"> String httpPostRequest(String url) {
</span><span style="color: #008080"> 88</span>         HttpPost httpPost = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpPost(url);
</span><span style="color: #008080"> 89</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpPost);
</span><span style="color: #008080"> 90</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 91</span> 
<span style="color: #008080"> 92</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String httpPostRequest(String url, Map<String, Object> params) <span style="color: #0000ff">throws</span><span style="color: #000000"> UnsupportedEncodingException {
</span><span style="color: #008080"> 93</span>         HttpPost httpPost = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpPost(url);
</span><span style="color: #008080"> 94</span>         ArrayList<NameValuePair> pairs =<span style="color: #000000"> covertParams2NVPS(params);
</span><span style="color: #008080"> 95</span>         httpPost.setEntity(<span style="color: #0000ff">new</span><span style="color: #000000"> UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));
</span><span style="color: #008080"> 96</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpPost);
</span><span style="color: #008080"> 97</span> <span style="color: #000000">    }
</span><span style="color: #008080"> 98</span> 
<span style="color: #008080"> 99</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object><span style="color: #000000"> params)
</span><span style="color: #008080">100</span>             <span style="color: #0000ff">throws</span><span style="color: #000000"> UnsupportedEncodingException {
</span><span style="color: #008080">101</span>         HttpPost httpPost = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpPost(url);
</span><span style="color: #008080">102</span> 
<span style="color: #008080">103</span>         <span style="color: #0000ff">for</span> (Map.Entry<String, Object><span style="color: #000000"> param : headers.entrySet()) {
</span><span style="color: #008080">104</span> <span style="color: #000000">            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
</span><span style="color: #008080">105</span> <span style="color: #000000">        }
</span><span style="color: #008080">106</span> 
<span style="color: #008080">107</span>         ArrayList<NameValuePair> pairs =<span style="color: #000000"> covertParams2NVPS(params);
</span><span style="color: #008080">108</span>         httpPost.setEntity(<span style="color: #0000ff">new</span><span style="color: #000000"> UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));
</span><span style="color: #008080">109</span> 
<span style="color: #008080">110</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpPost);
</span><span style="color: #008080">111</span> <span style="color: #000000">    }
</span><span style="color: #008080">112</span> 
<span style="color: #008080">113</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> String httpPostJSON(String url, String json) <span style="color: #0000ff">throws</span><span style="color: #000000"> UnsupportedEncodingException {
</span><span style="color: #008080">114</span>         HttpPost httpPost = <span style="color: #0000ff">new</span><span style="color: #000000"> HttpPost(url);
</span><span style="color: #008080">115</span>         StringEntity s = <span style="color: #0000ff">new</span><span style="color: #000000"> StringEntity(json);
</span><span style="color: #008080">116</span> <span style="color: #000000">        s.setContentEncoding(CONTENT_TYPE_UTF_8);
</span><span style="color: #008080">117</span>         s.setContentType(CONTENT_TYPE_JSON);<span style="color: #008000">//</span><span style="color: #008000"> 发送json数据需要设置contentType</span>
<span style="color: #008080">118</span> <span style="color: #000000">        httpPost.setEntity(s);
</span><span style="color: #008080">119</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> getResult(httpPost);
</span><span style="color: #008080">120</span> <span style="color: #000000">    }
</span><span style="color: #008080">121</span> 
<span style="color: #008080">122</span> 
<span style="color: #008080">123</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object><span style="color: #000000"> params) {
</span><span style="color: #008080">124</span>         ArrayList<NameValuePair> pairs = <span style="color: #0000ff">new</span> ArrayList<><span style="color: #000000">();
</span><span style="color: #008080">125</span>         <span style="color: #0000ff">for</span> (Map.Entry<String, Object><span style="color: #000000"> param : params.entrySet()) {
</span><span style="color: #008080">126</span>             pairs.add(<span style="color: #0000ff">new</span><span style="color: #000000"> BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
</span><span style="color: #008080">127</span> <span style="color: #000000">        }
</span><span style="color: #008080">128</span> 
<span style="color: #008080">129</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> pairs;
</span><span style="color: #008080">130</span> <span style="color: #000000">    }
</span><span style="color: #008080">131</span> 
<span style="color: #008080">132</span>     <span style="color: #008000">/**</span>
<span style="color: #008080">133</span> <span style="color: #008000">     * 处理Http请求
</span><span style="color: #008080">134</span> <span style="color: #008000">     *
</span><span style="color: #008080">135</span> <span style="color: #008000">     * </span><span style="color: #808080">@param</span><span style="color: #008000"> request
</span><span style="color: #008080">136</span> <span style="color: #008000">     * </span><span style="color: #808080">@return</span>
<span style="color: #008080">137</span>      <span style="color: #008000">*/</span>
<span style="color: #008080">138</span>     <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span><span style="color: #000000"> String getResult(HttpRequestBase request) {
</span><span style="color: #008080">139</span> 
<span style="color: #008080">140</span>         RequestConfig.Builder config =<span style="color: #000000"> RequestConfig.copy(RequestConfig.DEFAULT);
</span><span style="color: #008080">141</span> <span style="color: #000000">        config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
</span><span style="color: #008080">142</span> <span style="color: #000000">        config.setSocketTimeout(SO_TIMEOUT_MS);
</span><span style="color: #008080">143</span> 
<span style="color: #008080">144</span> <span style="color: #000000">        request.setConfig(config.build());
</span><span style="color: #008080">145</span> 
<span style="color: #008080">146</span>         <span style="color: #008000">//</span><span style="color: #008000"> CloseableHttpClient httpClient = HttpClients.createDefault();</span>
<span style="color: #008080">147</span>         CloseableHttpClient httpClient =<span style="color: #000000"> getHttpClient();
</span><span style="color: #008080">148</span>         CloseableHttpResponse response = <span style="color: #0000ff">null</span><span style="color: #000000">;
</span><span style="color: #008080">149</span>         <span style="color: #0000ff">try</span><span style="color: #000000"> {
</span><span style="color: #008080">150</span>             response =<span style="color: #000000"> httpClient.execute(request);
</span><span style="color: #008080">151</span>             <span style="color: #008000">//</span><span style="color: #008000"> response.getStatusLine().getStatusCode();</span>
<span style="color: #008080">152</span>             HttpEntity entity =<span style="color: #000000"> response.getEntity();
</span><span style="color: #008080">153</span>             <span style="color: #0000ff">if</span> (entity != <span style="color: #0000ff">null</span><span style="color: #000000">) {
</span><span style="color: #008080">154</span>                 <span style="color: #008000">//</span><span style="color: #008000"> long len = entity.getContentLength();</span><span style="color: #008000">//</span><span style="color: #008000"> -1 表示长度未知</span>
<span style="color: #008080">155</span>                 <span style="color: #0000ff">return</span><span style="color: #000000"> EntityUtils.toString(entity);
</span><span style="color: #008080">156</span> <span style="color: #000000">            }
</span><span style="color: #008080">157</span>         } <span style="color: #0000ff">catch</span><span style="color: #000000"> (IOException e) {
</span><span style="color: #008080">158</span> <span style="color: #000000">            e.printStackTrace();
</span><span style="color: #008080">159</span>         } <span style="color: #0000ff">finally</span><span style="color: #000000"> {
</span><span style="color: #008080">160</span>             <span style="color: #0000ff">try</span><span style="color: #000000"> {
</span><span style="color: #008080">161</span>                 <span style="color: #008000">//</span><span style="color: #008000"> 释放Socket流</span>
<span style="color: #008080">162</span> <span style="color: #000000">                response.close();
</span><span style="color: #008080">163</span>                 <span style="color: #008000">//</span><span style="color: #008000"> 释放Connection
</span><span style="color: #008080">164</span>                 <span style="color: #008000">//</span><span style="color: #008000"> httpClient.close();</span>
<span style="color: #008080">165</span>             } <span style="color: #0000ff">catch</span><span style="color: #000000"> (IOException e) {
</span><span style="color: #008080">166</span> <span style="color: #000000">                e.printStackTrace();
</span><span style="color: #008080">167</span> <span style="color: #000000">            }
</span><span style="color: #008080">168</span> <span style="color: #000000">        }
</span><span style="color: #008080">169</span> 
<span style="color: #008080">170</span>         <span style="color: #0000ff">return</span><span style="color: #000000"> EMPTY_STR;
</span><span style="color: #008080">171</span> <span style="color: #000000">    }
</span><span style="color: #008080">172</span> 
<span style="color: #008080">173</span> }
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal