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 ...
随机推荐
- adb命令总结
- Linux常用技巧
1.解决不能中文显示 xshell 终端语言显示选择UTF-8 #yum groupinstall chinese-support 2.heredocument报错“unexpected end of ...
- Odoo Documentation : Recordsets
Other recordset operations Recordsets are iterable(可迭代的) so the usual Python tools are available for ...
- MySQL系列(十一)--外键约束foreign key的基本使用
有些时候,为了保证数据的完整性,我们会选择的使用外键约束,例如教师对应的表和课程表中老师的id,这种时候就要使用外键约束了. PS:这里不考虑表结构设计,三范式与反范式等设计问题,基于MySQL8.0 ...
- linux平台进行c语言源码安装
安装c源程序的步骤: 1. ./configure --prefix 执行编译检测 指定安装路径 2. make 编译 3. sudo make install 编译后安装 前两步可以合成一步(mak ...
- linux 三剑客命令(grep,sed ,awk)
grep 命令 :强大的文本’搜索’工具 1.grep -n 'word' file_name 在file_name文件中找到word所在的所有行并显示.-n 为显示行号. 2 ...
- 批量操作文本文件进行dos/unix格式转换
批量将目录下所有文件进行 dos/unix 格式转换 使用 sed + grep #sed -i "s/原字符串/新字符串/g" `grep 原字符串 -rl 所在目录` eg: ...
- Firefox Developer Edition - Mozilla
冰狐浏览器开发者工具:https://www.mozilla.org/en-US/firefox/developer/ 冰狐浏览器开发者工具:https://www.mozilla.org/en-US ...
- 用VUE监听数组和对象的变化
看一下演示代码,先是增加数组和对象. <template> <div> <p>这是我定义的数组</p> <div>{{this.arr}}& ...
- js的剪贴板事件
定义 剪贴板操作包括剪切(cut).复制(copy)和粘贴(paste)这三个操作,快捷键分别是ctrl+x.ctrl+c.ctrl+v.当然也可以使用鼠标右键菜单进行操作 关于这3个操作共对应下列6 ...