HTTP请求封装Java工具类
装载自:http://www.open-open.com/lib/view/open1384844838743.html
package com.wiker;</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.BufferedReader; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.ByteArrayOutputStream; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.IOException; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.InputStream; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.InputStreamReader; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.OutputStream; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.HttpURLConnection; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.InetAddress; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.Socket; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.URL; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.URLConnection; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.net.URLEncoder; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.nio.charset.Charset; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.util.HashMap; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.util.Map; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.util.Map.Entry; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.util.Set; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.util.Vector; </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* </span><span style="color: #808080">@author</span><span style="color: #008000"> Wiker Yong Email:<a href="mailto:wikeryong@gmail.com">wikeryong@gmail.com</a> </br>
* @date 2013-11-8 下午7:22:43 </br>
* </span><span style="color: #808080">@version</span><span style="color: #008000"> 1.0-SNAPSHOT </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span><span style="color: #000000"> HttpUtils { </br></br> </span><span style="color: #0000ff">private</span><span style="color: #000000"> String defaultContentEncoding; </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> HttpUtils() { </br>
</span><span style="color: #0000ff">this</span>.defaultContentEncoding =<span style="color: #000000"> Charset.defaultCharset().name(); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送GET请求
*
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象</br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendGet(String urlString) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "GET", <span style="color: #0000ff">null</span>, <span style="color: #0000ff">null</span><span style="color: #000000">); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送GET请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params 参数集合 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendGet(String urlString, Map<String, String> params) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "GET", params, <span style="color: #0000ff">null</span><span style="color: #000000">); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送GET请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params 参数集合 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> propertys 请求属性 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendGet(String urlString, Map<String, String> params, Map<String, String><span style="color: #000000"> propertys) </br>
</span><span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "GET"<span style="color: #000000">, params, propertys); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送POST请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendPost(String urlString) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "POST", <span style="color: #0000ff">null</span>, <span style="color: #0000ff">null</span><span style="color: #000000">); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"></br>
* 发送POST请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params 参数集合 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendPost(String urlString, Map<String, String> params) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "POST", params, <span style="color: #0000ff">null</span><span style="color: #000000">); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送POST请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString URL地址 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params 参数集合 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> propertys 请求属性 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> HttpRespons sendPost(String urlString, Map<String, String> params, Map<String, String><span style="color: #000000"> propertys) </br>
</span><span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.send(urlString, "POST"<span style="color: #000000">, params, propertys); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送HTTP请求 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlString 地址 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> method get/post </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> parameters 添加由键值对指定的请求参数 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> propertys 添加由键值对指定的一般请求属性 </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响映对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException</br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span> HttpRespons send(String urlString, String method, Map<String, String><span style="color: #000000"> parameters, </br>
Map</span><String, String> propertys) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
HttpURLConnection urlConnection </span>= <span style="color: #0000ff">null</span><span style="color: #000000">; </br></br> </span><span style="color: #0000ff">if</span> (method.equalsIgnoreCase("GET") && parameters != <span style="color: #0000ff">null</span><span style="color: #000000">) { </br>
StringBuffer param </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuffer(); </br>
</span><span style="color: #0000ff">int</span> i = 0<span style="color: #000000">; </br>
</span><span style="color: #0000ff">for</span><span style="color: #000000"> (String key : parameters.keySet()) { </br>
</span><span style="color: #0000ff">if</span> (i == 0<span style="color: #000000">) </br>
param.append(</span>"?"<span style="color: #000000">); </br>
</span><span style="color: #0000ff">else</span><span style="color: #000000"> </br>
param.append(</span>"&"<span style="color: #000000">); </br>
param.append(key).append(</span>"="<span style="color: #000000">).append(parameters.get(key)); </br>
i</span>++<span style="color: #000000">; </br>
} </br>
urlString </span>+=<span style="color: #000000"> param; </br>
} </br></br> URL url </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> URL(urlString); </br>
urlConnection </span>=<span style="color: #000000"> (HttpURLConnection) url.openConnection(); </br>
urlConnection.setRequestMethod(method); </br>
urlConnection.setDoOutput(</span><span style="color: #0000ff">true</span><span style="color: #000000">); </br>
urlConnection.setDoInput(</span><span style="color: #0000ff">true</span><span style="color: #000000">); </br>
urlConnection.setUseCaches(</span><span style="color: #0000ff">false</span><span style="color: #000000">); </br></br> </span><span style="color: #0000ff">if</span> (propertys != <span style="color: #0000ff">null</span><span style="color: #000000">) </br>
</span><span style="color: #0000ff">for</span><span style="color: #000000"> (String key : propertys.keySet()) { </br>
urlConnection.addRequestProperty(key, propertys.get(key)); </br>
} </br></br> </span><span style="color: #0000ff">if</span> (method.equalsIgnoreCase("POST") && parameters != <span style="color: #0000ff">null</span><span style="color: #000000">) { </br>
StringBuffer param </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuffer(); </br>
</span><span style="color: #0000ff">for</span><span style="color: #000000"> (String key : parameters.keySet()) { </br>
param.append(</span>"&"<span style="color: #000000">); </br>
param.append(key).append(</span>"="<span style="color: #000000">).append(parameters.get(key)); </br>
} </br>
urlConnection.getOutputStream().write(param.toString().getBytes()); </br>
urlConnection.getOutputStream().flush(); </br>
urlConnection.getOutputStream().close(); </br>
} </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span><span style="color: #000000">.makeContent(urlString, urlConnection); </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 得到响应对象 </br>
* </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> urlConnection </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> 响应对象 </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> IOException </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span> HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) <span style="color: #0000ff">throws</span><span style="color: #000000"> IOException { </br>
HttpRespons httpResponser </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> HttpRespons(); </br>
</span><span style="color: #0000ff">try</span><span style="color: #000000"> { </br>
InputStream in </span>=<span style="color: #000000"> urlConnection.getInputStream(); </br>
BufferedReader bufferedReader </span>= <span style="color: #0000ff">new</span> BufferedReader(<span style="color: #0000ff">new</span><span style="color: #000000"> InputStreamReader(in)); </br>
httpResponser.contentCollection </span>= <span style="color: #0000ff">new</span> Vector<String><span style="color: #000000">(); </br>
StringBuffer temp </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuffer(); </br>
String line </span>=<span style="color: #000000"> bufferedReader.readLine(); </br>
</span><span style="color: #0000ff">while</span> (line != <span style="color: #0000ff">null</span><span style="color: #000000">) { </br>
httpResponser.contentCollection.add(line); </br>
temp.append(line).append(</span>"\r\n"<span style="color: #000000">); </br>
line </span>=<span style="color: #000000"> bufferedReader.readLine();</br>
} </br>
bufferedReader.close(); </br>
String ecod </span>=<span style="color: #000000"> urlConnection.getContentEncoding(); </br>
</span><span style="color: #0000ff">if</span> (ecod == <span style="color: #0000ff">null</span><span style="color: #000000">) </br>
ecod </span>= <span style="color: #0000ff">this</span><span style="color: #000000">.defaultContentEncoding; </br>
httpResponser.urlString </span>=<span style="color: #000000"> urlString; </br>
httpResponser.defaultPort </span>=<span style="color: #000000"> urlConnection.getURL().getDefaultPort(); </br>
httpResponser.file </span>=<span style="color: #000000"> urlConnection.getURL().getFile(); </br>
httpResponser.host </span>=<span style="color: #000000"> urlConnection.getURL().getHost(); </br>
httpResponser.path </span>=<span style="color: #000000"> urlConnection.getURL().getPath(); </br>
httpResponser.port </span>=<span style="color: #000000"> urlConnection.getURL().getPort(); </br>
httpResponser.protocol </span>=<span style="color: #000000"> urlConnection.getURL().getProtocol(); </br>
httpResponser.query </span>=<span style="color: #000000"> urlConnection.getURL().getQuery(); </br>
httpResponser.ref </span>=<span style="color: #000000"> urlConnection.getURL().getRef(); </br>
httpResponser.userInfo </span>=<span style="color: #000000"> urlConnection.getURL().getUserInfo(); </br>
httpResponser.content </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> String(temp.toString().getBytes(), ecod); </br>
httpResponser.contentEncoding </span>=<span style="color: #000000"> ecod; </br>
httpResponser.code </span>=<span style="color: #000000"> urlConnection.getResponseCode(); </br>
httpResponser.message </span>=<span style="color: #000000"> urlConnection.getResponseMessage(); </br>
httpResponser.contentType </span>=<span style="color: #000000"> urlConnection.getContentType(); </br>
httpResponser.method </span>=<span style="color: #000000"> urlConnection.getRequestMethod(); </br>
httpResponser.connectTimeout </span>=<span style="color: #000000"> urlConnection.getConnectTimeout(); </br>
httpResponser.readTimeout </span>=<span style="color: #000000"> urlConnection.getReadTimeout(); </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> httpResponser; </br>
} </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (IOException e) { </br>
</span><span style="color: #0000ff">throw</span><span style="color: #000000"> e; </br>
} </span><span style="color: #0000ff">finally</span><span style="color: #000000"> { </br>
</span><span style="color: #0000ff">if</span> (urlConnection != <span style="color: #0000ff">null</span><span style="color: #000000">) </br>
urlConnection.disconnect();</br>
} </br>
} </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 默认的响应字符集 </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span><span style="color: #000000"> String getDefaultContentEncoding() { </br>
</span><span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span><span style="color: #000000">.defaultContentEncoding; </br>
} </br></br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送GET请求 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> url </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> headers </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span><span style="color: #000000"> URLConnection sendGetRequest(String url,
Map</span><String, String> params, Map<String, String><span style="color: #000000"> headers) </br>
</span><span style="color: #0000ff">throws</span><span style="color: #000000"> Exception { </br>
StringBuilder buf </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuilder(url); </br>
Set</span><Entry<String, String>> entrys = <span style="color: #0000ff">null</span><span style="color: #000000">; </br>
</span><span style="color: #008000">//</span><span style="color: #008000"> 如果是GET请求,则请求参数在URL中 </span></br>
<span style="color: #0000ff">if</span> (params != <span style="color: #0000ff">null</span> && !<span style="color: #000000">params.isEmpty()) { </br>
buf.append(</span>"?"<span style="color: #000000">); </br>
entrys </span>=<span style="color: #000000"> params.entrySet(); </br>
</span><span style="color: #0000ff">for</span> (Map.Entry<String, String><span style="color: #000000"> entry : entrys) { </br>
buf.append(entry.getKey()).append(</span>"="<span style="color: #000000">) </br>
.append(URLEncoder.encode(entry.getValue(), </span>"UTF-8"<span style="color: #000000">)) </br>
.append(</span>"&"<span style="color: #000000">); </br>
} </br>
buf.deleteCharAt(buf.length() </span>- 1<span style="color: #000000">); </br>
} </br>
URL url1 </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> URL(buf.toString()); </br>
HttpURLConnection conn </span>=<span style="color: #000000"> (HttpURLConnection) url1.openConnection(); </br>
conn.setRequestMethod(</span>"GET"<span style="color: #000000">); </br>
</span><span style="color: #008000">//</span><span style="color: #008000"> 设置请求头 </span></br>
<span style="color: #0000ff">if</span> (headers != <span style="color: #0000ff">null</span> && !<span style="color: #000000">headers.isEmpty()) { </br>
entrys </span>=<span style="color: #000000"> headers.entrySet(); </br>
</span><span style="color: #0000ff">for</span> (Map.Entry<String, String><span style="color: #000000"> entry : entrys) { </br>
conn.setRequestProperty(entry.getKey(), entry.getValue()); </br>
} </br>
} </br>
conn.getResponseCode(); </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> conn; </br>
} </br>
</span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 发送POST请求 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> url </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> headers </br>
* </span><span style="color: #808080">@return</span><span style="color: #008000"> </br>
* </span><span style="color: #808080">@throws</span><span style="color: #008000"> Exception </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span><span style="color: #000000"> URLConnection sendPostRequest(String url, </br>
Map</span><String, String> params, Map<String, String><span style="color: #000000"> headers) </br>
</span><span style="color: #0000ff">throws</span><span style="color: #000000"> Exception { </br>
StringBuilder buf </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuilder(); </br>
Set</span><Entry<String, String>> entrys = <span style="color: #0000ff">null</span><span style="color: #000000">; </br>
</span><span style="color: #008000">//</span><span style="color: #008000"> 如果存在参数,则放在HTTP请求体,形如name=aaa&age=10 </span></br>
<span style="color: #0000ff">if</span> (params != <span style="color: #0000ff">null</span> && !<span style="color: #000000">params.isEmpty()) { </br>
entrys </span>=<span style="color: #000000"> params.entrySet(); </br>
</span><span style="color: #0000ff">for</span> (Map.Entry<String, String><span style="color: #000000"> entry : entrys) { </br>
buf.append(entry.getKey()).append(</span>"="<span style="color: #000000">) </br>
.append(URLEncoder.encode(entry.getValue(), </span>"UTF-8"<span style="color: #000000">)) </br>
.append(</span>"&"<span style="color: #000000">); </br>
} </br>
buf.deleteCharAt(buf.length() </span>- 1<span style="color: #000000">); </br>
} </br>
URL url1 </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> URL(url);</br>
HttpURLConnection conn </span>=<span style="color: #000000"> (HttpURLConnection) url1.openConnection();</br>
conn.setRequestMethod(</span>"POST"<span style="color: #000000">); </br>
conn.setDoOutput(</span><span style="color: #0000ff">true</span><span style="color: #000000">); </br>
OutputStream out </span>=<span style="color: #000000"> conn.getOutputStream(); </br>
out.write(buf.toString().getBytes(</span>"UTF-8"<span style="color: #000000">)); </br>
</span><span style="color: #0000ff">if</span> (headers != <span style="color: #0000ff">null</span> && !<span style="color: #000000">headers.isEmpty()) { </br>
entrys </span>=<span style="color: #000000"> headers.entrySet(); </br>
</span><span style="color: #0000ff">for</span> (Map.Entry<String, String><span style="color: #000000"> entry : entrys) { </br>
conn.setRequestProperty(entry.getKey(), entry.getValue()); </br>
} </br>
} </br>
conn.getResponseCode(); </span><span style="color: #008000">//</span><span style="color: #008000"> 为了发送成功 </span></br>
<span style="color: #0000ff">return</span><span style="color: #000000"> conn; </br>
} </br>
</span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: </br>
* <FORM METHOD=POST ACTION="</span><span style="color: #008000; text-decoration: underline">http://192.168.0.200</span><span style="color: #008000">:8080/ssi/fileload/test.do" enctype="multipart/form-data"> </br>
<INPUT TYPE="text" NAME="name"> </br>
<INPUT TYPE="text" NAME="id"> </br>
<input type="file" name="imagefile"/> </br>
<input type="file" name="zip"/> </br>
</FORM> </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试) </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> params 请求参数 key为参数名,value为参数值 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> file 上传文件 </br>
</span><span style="color: #008000">*/</span></br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">boolean</span> uploadFiles(String path, Map<String, String> params, FormFile[] files) <span style="color: #0000ff">throws</span><span style="color: #000000"> Exception{ </br>
</span><span style="color: #0000ff">final</span> String BOUNDARY = "---------------------------7da2137580612"; <span style="color: #008000">//</span><span style="color: #008000">数据分隔线 </span></br>
<span style="color: #0000ff">final</span> String endline = "--" + BOUNDARY + "--\r\n";<span style="color: #008000">//</span><span style="color: #008000">数据结束标志 </span></br></br> <span style="color: #0000ff">int</span> fileDataLength = 0<span style="color: #000000">; </br>
</span><span style="color: #0000ff">if</span>(files!=<span style="color: #0000ff">null</span>&&files.length!=0<span style="color: #000000">){ </br>
</span><span style="color: #0000ff">for</span>(FormFile uploadFile : files){<span style="color: #008000">//</span><span style="color: #008000">得到文件类型数据的总长度 </span></br>
StringBuilder fileExplain = <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuilder(); </br>
fileExplain.append(</span>"--"<span style="color: #000000">); </br>
fileExplain.append(BOUNDARY); </br>
fileExplain.append(</span>"\r\n"<span style="color: #000000">); </br>
fileExplain.append(</span>"Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n"<span style="color: #000000">); </br>
fileExplain.append(</span>"Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"<span style="color: #000000">); </br>
fileExplain.append(</span>"\r\n"<span style="color: #000000">); </br>
fileDataLength </span>+=<span style="color: #000000"> fileExplain.length(); </br>
</span><span style="color: #0000ff">if</span>(uploadFile.getInStream()!=<span style="color: #0000ff">null</span><span style="color: #000000">){ </br>
fileDataLength </span>+=<span style="color: #000000"> uploadFile.getFile().length(); </br>
}</span><span style="color: #0000ff">else</span><span style="color: #000000">{ </br>
fileDataLength </span>+=<span style="color: #000000"> uploadFile.getData().length; </br>
} </br>
} </br>
} </br>
StringBuilder textEntity </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> StringBuilder(); </br>
</span><span style="color: #0000ff">if</span>(params!=<span style="color: #0000ff">null</span>&&!<span style="color: #000000">params.isEmpty()){ </br>
</span><span style="color: #0000ff">for</span> (Map.Entry<String, String> entry : params.entrySet()) {<span style="color: #008000">//</span><span style="color: #008000">构造文本类型参数的实体数据 </span></br>
textEntity.append("--"<span style="color: #000000">); </br>
textEntity.append(BOUNDARY); </br>
textEntity.append(</span>"\r\n"<span style="color: #000000">); </br>
textEntity.append(</span>"Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n"<span style="color: #000000">); </br>
textEntity.append(entry.getValue()); </br>
textEntity.append(</span>"\r\n"<span style="color: #000000">); </br>
} </br>
} </br>
</span><span style="color: #008000">//</span><span style="color: #008000">计算传输给服务器的实体数据总长度 </span></br>
<span style="color: #0000ff">int</span> dataLength = textEntity.toString().getBytes().length + fileDataLength +<span style="color: #000000"> endline.getBytes().length; </br></br> URL url </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> URL(path); </br>
</span><span style="color: #0000ff">int</span> port = url.getPort()==-1 ? 80<span style="color: #000000"> : url.getPort(); </br>
Socket socket </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> Socket(InetAddress.getByName(url.getHost()), port); </br>
OutputStream outStream </span>=<span style="color: #000000"> socket.getOutputStream(); </br>
</span><span style="color: #008000">//</span><span style="color: #008000">下面完成HTTP请求头的发送 </span></br>
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n"<span style="color: #000000">; </br>
outStream.write(requestmethod.getBytes()); </br>
String accept </span>= "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"<span style="color: #000000">; </br>
outStream.write(accept.getBytes()); </br>
String language </span>= "Accept-Language: zh-CN\r\n"<span style="color: #000000">; </br>
outStream.write(language.getBytes()); </br>
String contenttype </span>= "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n"<span style="color: #000000">;</br>
outStream.write(contenttype.getBytes()); </br>
String contentlength </span>= "Content-Length: "+ dataLength + "\r\n"<span style="color: #000000">; </br>
outStream.write(contentlength.getBytes()); </br>
String alive </span>= "Connection: Keep-Alive\r\n"<span style="color: #000000">; </br>
outStream.write(alive.getBytes()); </br>
String host </span>= "Host: "+ url.getHost() +":"+ port +"\r\n"<span style="color: #000000">; </br>
outStream.write(host.getBytes()); </br>
</span><span style="color: #008000">//</span><span style="color: #008000">写完HTTP请求头后根据HTTP协议再写一个回车换行 </span></br>
outStream.write("\r\n"<span style="color: #000000">.getBytes()); </br>
</span><span style="color: #008000">//</span><span style="color: #008000">把所有文本类型的实体数据发送出来 </span></br>
outStream.write(textEntity.toString().getBytes());
//把所有文件类型的实体数据发送出来
if(files!=null&&files.length!=0){
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=""+ uploadFile.getParameterName()+"";filename=""+ uploadFile.getFilname() + ""\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if(uploadFile.getInStream()!=null){
byte[] buffer = new byte[1024];
int len = 0;
while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
}
uploadFile.getInStream().close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
}
//下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/
* 提交数据到服务器
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean uploadFile(String path, Map<String, String> params, FormFile file) throws Exception{
return uploadFiles(path, params, new FormFile[]{file});
}
/
* 将输入流转为字节数组
* @param inStream
* @return
* @throws Exception
/
public static byte[] read2Byte(InputStream inStream)throws Exception{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) !=-1 ){
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
/**
* 将输入流转为字符串
* @param inStream
* @return
* @throws Exception
/
public static String read2String(InputStream inStream)throws Exception{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) !=-1 ){
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return new String(outSteam.toByteArray(),"UTF-8");
}
/**
* 发送xml数据
* @param path 请求地址
* @param xml xml数据
* @param encoding 编码
* @return
* @throws Exception
*/
public static byte[] postXml(String path, String xml, String encoding) throws Exception{
byte[] data = xml.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if(conn.getResponseCode()200){
return read2Byte(conn.getInputStream());
}
return null;
}
//测试函数
public static void main(String args[]) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "xiazdong");
params.put("age", "10");
HttpURLConnection conn = (HttpURLConnection)
sendGetRequest(
"http://192.168.0.103:8080/Server/PrintServlet",
params, null);
int code = conn.getResponseCode();
InputStream in = conn.getInputStream();
byte[]data = read2Byte(in);
}</span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 设置默认的响应字符集 </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setDefaultContentEncoding(String defaultContentEncoding) { </br>
</span><span style="color: #0000ff">this</span>.defaultContentEncoding =<span style="color: #000000"> defaultContentEncoding; </br>
} </br>
} </br>
需要引用到的文件FormFile.java如下:
package com.wiker;</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.File; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.FileInputStream; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.FileNotFoundException; </br>
</span><span style="color: #0000ff">import</span><span style="color: #000000"> java.io.InputStream; </br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 上传文件
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span><span style="color: #000000"> FormFile { </br>
</span><span style="color: #008000">/*</span><span style="color: #008000"> 上传文件的数据 </span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">byte</span><span style="color: #000000">[] data; </br>
</span><span style="color: #0000ff">private</span><span style="color: #000000"> InputStream inStream; </br>
</span><span style="color: #0000ff">private</span><span style="color: #000000"> File file; </br>
</span><span style="color: #008000">/*</span><span style="color: #008000"> 文件名称 </span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span><span style="color: #000000"> String filname; </br>
</span><span style="color: #008000">/*</span><span style="color: #008000"> 请求参数名称</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span><span style="color: #000000"> String parameterName; </br>
</span><span style="color: #008000">/*</span><span style="color: #008000"> 内容类型 </span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">private</span> String contentType = "application/octet-stream"<span style="color: #000000">; </br></br> </span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 此函数用来传输小文件 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> filname </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> data </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> parameterName </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> contentType </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span> FormFile(String filname, <span style="color: #0000ff">byte</span><span style="color: #000000">[] data, String parameterName, String contentType) { </br>
</span><span style="color: #0000ff">this</span>.data =<span style="color: #000000"> data; </br>
</span><span style="color: #0000ff">this</span>.filname =<span style="color: #000000"> filname; </br>
</span><span style="color: #0000ff">this</span>.parameterName =<span style="color: #000000"> parameterName; </br>
</span><span style="color: #0000ff">if</span>(contentType!=<span style="color: #0000ff">null</span>) <span style="color: #0000ff">this</span>.contentType =<span style="color: #000000"> contentType; </br>
} </br>
</span><span style="color: #008000">/**</span><span style="color: #008000"> </br>
* 此函数用来传输大文件 </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> filname </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> file </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> parameterName </br>
* </span><span style="color: #808080">@param</span><span style="color: #008000"> contentType </br>
</span><span style="color: #008000">*/</span> </br>
<span style="color: #0000ff">public</span><span style="color: #000000"> FormFile(String filname, File file, String parameterName, String contentType) { </br>
</span><span style="color: #0000ff">this</span>.filname =<span style="color: #000000"> filname; </br>
</span><span style="color: #0000ff">this</span>.parameterName =<span style="color: #000000"> parameterName; </br>
</span><span style="color: #0000ff">this</span>.file =<span style="color: #000000"> file; </br>
</span><span style="color: #0000ff">try</span><span style="color: #000000"> { </br>
</span><span style="color: #0000ff">this</span>.inStream = <span style="color: #0000ff">new</span><span style="color: #000000"> FileInputStream(file); </br>
} </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (FileNotFoundException e) { </br>
e.printStackTrace(); </br>
} </br>
</span><span style="color: #0000ff">if</span>(contentType!=<span style="color: #0000ff">null</span>) <span style="color: #0000ff">this</span>.contentType =<span style="color: #000000"> contentType; </br>
} </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> File getFile() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> file; </br>
} </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> InputStream getInStream() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> inStream; </br>
} </br></br> </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">byte</span><span style="color: #000000">[] getData() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> data; </br>
} </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getFilname() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> filname; </br>
} </br></br> </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setFilname(String filname) { </br>
</span><span style="color: #0000ff">this</span>.filname =<span style="color: #000000"> filname; </br>
} </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getParameterName() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> parameterName; </br>
} </br></br> </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setParameterName(String parameterName) { </br>
</span><span style="color: #0000ff">this</span>.parameterName =<span style="color: #000000"> parameterName; </br>
} </br></br> </span><span style="color: #0000ff">public</span><span style="color: #000000"> String getContentType() { </br>
</span><span style="color: #0000ff">return</span><span style="color: #000000"> contentType; </br>
} </br></br> </span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> setContentType(String contentType) { </br>
</span><span style="color: #0000ff">this</span>.contentType =<span style="color: #000000"> contentType; </br>
} </br></br> } </span></pre>
HTTP请求封装Java工具类的更多相关文章
- JAVA中封装JSONUtils工具类及使用
在JAVA中用json-lib-2.3-jdk15.jar包中提供了JSONObject和JSONArray基类,用于JSON的序列化和反序列化的操作.但是我们更习惯将其进一步封装,达到更好的重用. ...
- 打印 Logger 日志时,需不需要再封装一下工具类?
在开发过程中,打印日志是必不可少的,因为日志关乎于应用的问题排查.应用监控等.现在打印日志一般都是使用 slf4j,因为使用日志门面,有助于打印方式统一,即使后面更换日志框架,也非常方便.在 < ...
- MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- MySQL JDBC事务处理、封装JDBC工具类
MySQL数据库学习笔记(十)----JDBC事务处理.封装JDBC工具类 一.JDBC事务处理: 我们已经知道,事务的概念即:所有的操作要么同时成功,要么同时失败.在MySQL中提供了Commit. ...
- DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...
- Workbook导出excel封装的工具类
在实际中导出excel非常常见,于是自己封装了一个导出数据到excel的工具类,先附上代码,最后会写出实例和解释.支持03和07两个版本的 excel. HSSF导出的是xls的excel,XSSF导 ...
- 封装JDBC工具类
JDBC连接数据库基本的步骤是固定的,这样就可以考虑封装一个工具类来简化数据库操作. 封装时用到了Java中的properties配置文件,是以一种键值对的形式存在的,可以把连接数据库要动态的信息保存 ...
- writeValueAsString封装成工具类
封装成工具类 <span style="font-family:Microsoft YaHei;">public static String toJsonByObjec ...
随机推荐
- php 7.2下mcrypt扩展支持附带的问题
按照网上提供的mcrypt扩展编译支持方法,完成了扩展编译,也确实可以正常加密/解密了 但是如果php.ini中配置为: error_reporting = E_ALL display_errors ...
- CAS客户端配置
1. 导出证书 以上操作会在当前目录产生文件:ssodemo.crt(需要用到的文件请看CAS服务端配置那篇文章) 2. 客户端导入证书 以上操作会在jdk安装目录jre\lib\security下产 ...
- js时间比较大小,时间加减
第一种: //时间类比较 startTime= new Date(Date.parse(starttime)); endTime=new Date(Date.parse(endTime)); //进行 ...
- Windows API 第二篇 SHGetSpecialFolderPath
BOOL SHGetSpecialFolderPath( HWND hwndOwner, LPTSTR lpszPath, ...
- 【心无旁骛】vuex-typescript-example
我不惮以最大的赞美去赞美这样的项目,真的是非常有创意又有能力. 先放上我喜欢的这个项目的开源地址:https://github.com/gluons/vuex-typescript-example 我 ...
- SyntaxError: Non-ASCII character ‘xe5’ in file 04.py on line 4, but no encoding declared
出现问题的原因:程序中的编码错误,python默认是acii模式,没有支持utf8,代码中需要输出汉字,所以报错. 解决办法:源代码文件第一行添加:#coding:utf-8 -- coding: U ...
- [转]WPF中的动画
WPF中的动画 周银辉 动画无疑是WP ...
- 工控安全入门(四)—— DNP3协议
我们之前看过了法国施耐德的Modbus.德国西门子的S7comm,这次就让我们把目光投到美洲,看看加拿大的HARRIS的DNP3有什么特别之处. 这次选用的流量包部分来自w3h的gitbub: htt ...
- 机器学习中的隐马尔科夫模型(HMM)详解
机器学习中的隐马尔科夫模型(HMM)详解 在之前介绍贝叶斯网络的博文中,我们已经讨论过概率图模型(PGM)的概念了.Russell等在文献[1]中指出:"在统计学中,图模型这个术语指包含贝叶 ...
- MyBatis-Spring(三)--Mapped Statements collection does not contain value for...问题解决
前一篇文章我总结了一下MyBatis-Spring项目使用SqlSessionTemplate配置的用法,其实在测试过程中并不是一帆风顺,遇到了很多的问题,最主要的就是Mapped Statement ...