import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; /**
* @Description:发送http请求帮助类
* @author:liuyc
* @time:2016年5月17日 下午3:25:32
*/
public class HttpClientHelper {
/**
* @Description:使用HttpURLConnection发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:26:07
*/
public static String sendPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
// 发送请求
try {
URL url = new URL(urlParam);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (sbParams != null && sbParams.length() > 0) {
osw = new OutputStreamWriter(con.getOutputStream(), charset);
osw.write(sbParams.substring(0, sbParams.length() - 1));
osw.flush();
}
// 读取返回内容
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
} return resultBuffer.toString();
} /**
* @Description:使用URLConnection发送post
* @author:liuyc
* @time:2016年5月17日 下午3:26:52
*/
public static String sendPost2(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
URLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(urlParam);
// 打开和URL之间的连接
con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(con.getOutputStream(), charset);
if (sbParams != null && sbParams.length() > 0) {
// 发送请求参数
osw.write(sbParams.substring(0, sbParams.length() - 1));
// flush输出流的缓冲
osw.flush();
}
// 定义BufferedReader输入流来读取URL的响应
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:发送get请求保存下载文件
* @author:liuyc
* @time:2016年5月17日 下午3:27:29
*/
public static void sendGetAndSaveFile(String urlParam, Map<String, Object> params, String fileSavePath) {
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
BufferedReader br = null;
FileOutputStream os = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
InputStream is = con.getInputStream();
os = new FileOutputStream(fileSavePath);
byte buf[] = new byte[1024];
int count = 0;
while ((count = is.read(buf)) != -1) {
os.write(buf, 0, count);
}
os.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
os = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
} /**
* @Description:使用HttpURLConnection发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:27:29
*/
public static String sendGet(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用URLConnection发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:27:58
*/
public static String sendGet2(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
URLConnection con = url.openConnection();
// 设置请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立连接
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用HttpClient发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:28:23
*/
public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlParam);
// 构建请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> elem = iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
BufferedReader br = null;
try {
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = client.execute(httpPost);
// 读取服务器响应数据
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用HttpClient发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:28:56
*/
public static String httpClientGet(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
BufferedReader br = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
try {
sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
sbParams.append("&");
}
}
if (sbParams != null && sbParams.length() > 0) {
urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
}
HttpGet httpGet = new HttpGet(urlParam);
try {
HttpResponse response = client.execute(httpGet);
// 读取服务器响应数据
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
resultBuffer = new StringBuffer();
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用socket发送post请求
* @author:liuyc
* @time:2016年5月18日 上午9:26:22
*/
public static String sendSocketPost(String urlParam, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlParam);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("POST " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} /**
* @Description:使用socket发送get请求
* @author:liuyc
* @time:2016年5月18日 上午9:27:18
*/
public static String sendSocketGet(String urlParam, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlParam);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("GET " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} /**
* @Description:读取一行数据,contentLe内容长度为0时,读取响应头信息,不为0时读正文
* @time:2016年5月17日 下午6:11:07
*/
private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
List<Byte> lineByte = new ArrayList<Byte>();
byte tempByte;
int cumsum = 0;
if (contentLength != 0) {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
cumsum++;
} while (cumsum < contentLength);// cumsum等于contentLength表示已读完
} else {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
} while (tempByte != 10);// 换行符的ascii码值为10
} byte[] resutlBytes = new byte[lineByte.size()];
for (int i = 0; i < lineByte.size(); i++) {
resutlBytes[i] = (lineByte.get(i)).byteValue();
}
return new String(resutlBytes, charset);
} }
  1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.HttpURLConnection;
  8. import java.net.Socket;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.net.URLEncoder;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Map.Entry;
  18. import org.apache.http.HttpResponse;
  19. import org.apache.http.NameValuePair;
  20. import org.apache.http.client.HttpClient;
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;
  22. import org.apache.http.client.methods.HttpGet;
  23. import org.apache.http.client.methods.HttpPost;
  24. import org.apache.http.impl.client.DefaultHttpClient;
  25. import org.apache.http.message.BasicNameValuePair;
  26. /**
  27. * @Description:发送http请求帮助类
  28. * @author:liuyc
  29. * @time:2016年5月17日 下午3:25:32
  30. */
  31. public class HttpClientHelper {
  32. /**
  33. * @Description:使用HttpURLConnection发送post请求
  34. * @author:liuyc
  35. * @time:2016年5月17日 下午3:26:07
  36. */
  37. public static String sendPost(String urlParam, Map<String, Object> params, String charset) {
  38. StringBuffer resultBuffer = null;
  39. // 构建请求参数
  40. StringBuffer sbParams = new StringBuffer();
  41. if (params != null && params.size() > 0) {
  42. for (Entry<String, Object> e : params.entrySet()) {
  43. sbParams.append(e.getKey());
  44. sbParams.append("=");
  45. sbParams.append(e.getValue());
  46. sbParams.append("&");
  47. }
  48. }
  49. HttpURLConnection con = null;
  50. OutputStreamWriter osw = null;
  51. BufferedReader br = null;
  52. // 发送请求
  53. try {
  54. URL url = new URL(urlParam);
  55. con = (HttpURLConnection) url.openConnection();
  56. con.setRequestMethod("POST");
  57. con.setDoOutput(true);
  58. con.setDoInput(true);
  59. con.setUseCaches(false);
  60. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  61. if (sbParams != null && sbParams.length() > 0) {
  62. osw = new OutputStreamWriter(con.getOutputStream(), charset);
  63. osw.write(sbParams.substring(0, sbParams.length() - 1));
  64. osw.flush();
  65. }
  66. // 读取返回内容
  67. resultBuffer = new StringBuffer();
  68. int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
  69. if (contentLength > 0) {
  70. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  71. String temp;
  72. while ((temp = br.readLine()) != null) {
  73. resultBuffer.append(temp);
  74. }
  75. }
  76. } catch (Exception e) {
  77. throw new RuntimeException(e);
  78. } finally {
  79. if (osw != null) {
  80. try {
  81. osw.close();
  82. } catch (IOException e) {
  83. osw = null;
  84. throw new RuntimeException(e);
  85. } finally {
  86. if (con != null) {
  87. con.disconnect();
  88. con = null;
  89. }
  90. }
  91. }
  92. if (br != null) {
  93. try {
  94. br.close();
  95. } catch (IOException e) {
  96. br = null;
  97. throw new RuntimeException(e);
  98. } finally {
  99. if (con != null) {
  100. con.disconnect();
  101. con = null;
  102. }
  103. }
  104. }
  105. }
  106. return resultBuffer.toString();
  107. }
  108. /**
  109. * @Description:使用URLConnection发送post
  110. * @author:liuyc
  111. * @time:2016年5月17日 下午3:26:52
  112. */
  113. public static String sendPost2(String urlParam, Map<String, Object> params, String charset) {
  114. StringBuffer resultBuffer = null;
  115. // 构建请求参数
  116. StringBuffer sbParams = new StringBuffer();
  117. if (params != null && params.size() > 0) {
  118. for (Entry<String, Object> e : params.entrySet()) {
  119. sbParams.append(e.getKey());
  120. sbParams.append("=");
  121. sbParams.append(e.getValue());
  122. sbParams.append("&");
  123. }
  124. }
  125. URLConnection con = null;
  126. OutputStreamWriter osw = null;
  127. BufferedReader br = null;
  128. try {
  129. URL realUrl = new URL(urlParam);
  130. // 打开和URL之间的连接
  131. con = realUrl.openConnection();
  132. // 设置通用的请求属性
  133. con.setRequestProperty("accept", "*/*");
  134. con.setRequestProperty("connection", "Keep-Alive");
  135. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  136. con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  137. // 发送POST请求必须设置如下两行
  138. con.setDoOutput(true);
  139. con.setDoInput(true);
  140. // 获取URLConnection对象对应的输出流
  141. osw = new OutputStreamWriter(con.getOutputStream(), charset);
  142. if (sbParams != null && sbParams.length() > 0) {
  143. // 发送请求参数
  144. osw.write(sbParams.substring(0, sbParams.length() - 1));
  145. // flush输出流的缓冲
  146. osw.flush();
  147. }
  148. // 定义BufferedReader输入流来读取URL的响应
  149. resultBuffer = new StringBuffer();
  150. int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
  151. if (contentLength > 0) {
  152. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  153. String temp;
  154. while ((temp = br.readLine()) != null) {
  155. resultBuffer.append(temp);
  156. }
  157. }
  158. } catch (Exception e) {
  159. throw new RuntimeException(e);
  160. } finally {
  161. if (osw != null) {
  162. try {
  163. osw.close();
  164. } catch (IOException e) {
  165. osw = null;
  166. throw new RuntimeException(e);
  167. }
  168. }
  169. if (br != null) {
  170. try {
  171. br.close();
  172. } catch (IOException e) {
  173. br = null;
  174. throw new RuntimeException(e);
  175. }
  176. }
  177. }
  178. return resultBuffer.toString();
  179. }
  180. /**
  181. * @Description:发送get请求保存下载文件
  182. * @author:liuyc
  183. * @time:2016年5月17日 下午3:27:29
  184. */
  185. public static void sendGetAndSaveFile(String urlParam, Map<String, Object> params, String fileSavePath) {
  186. // 构建请求参数
  187. StringBuffer sbParams = new StringBuffer();
  188. if (params != null && params.size() > 0) {
  189. for (Entry<String, Object> entry : params.entrySet()) {
  190. sbParams.append(entry.getKey());
  191. sbParams.append("=");
  192. sbParams.append(entry.getValue());
  193. sbParams.append("&");
  194. }
  195. }
  196. HttpURLConnection con = null;
  197. BufferedReader br = null;
  198. FileOutputStream os = null;
  199. try {
  200. URL url = null;
  201. if (sbParams != null && sbParams.length() > 0) {
  202. url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
  203. } else {
  204. url = new URL(urlParam);
  205. }
  206. con = (HttpURLConnection) url.openConnection();
  207. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  208. con.connect();
  209. InputStream is = con.getInputStream();
  210. os = new FileOutputStream(fileSavePath);
  211. byte buf[] = new byte[1024];
  212. int count = 0;
  213. while ((count = is.read(buf)) != -1) {
  214. os.write(buf, 0, count);
  215. }
  216. os.flush();
  217. } catch (Exception e) {
  218. throw new RuntimeException(e);
  219. } finally {
  220. if (os != null) {
  221. try {
  222. os.close();
  223. } catch (IOException e) {
  224. os = null;
  225. throw new RuntimeException(e);
  226. } finally {
  227. if (con != null) {
  228. con.disconnect();
  229. con = null;
  230. }
  231. }
  232. }
  233. if (br != null) {
  234. try {
  235. br.close();
  236. } catch (IOException e) {
  237. br = null;
  238. throw new RuntimeException(e);
  239. } finally {
  240. if (con != null) {
  241. con.disconnect();
  242. con = null;
  243. }
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * @Description:使用HttpURLConnection发送get请求
  250. * @author:liuyc
  251. * @time:2016年5月17日 下午3:27:29
  252. */
  253. public static String sendGet(String urlParam, Map<String, Object> params, String charset) {
  254. StringBuffer resultBuffer = null;
  255. // 构建请求参数
  256. StringBuffer sbParams = new StringBuffer();
  257. if (params != null && params.size() > 0) {
  258. for (Entry<String, Object> entry : params.entrySet()) {
  259. sbParams.append(entry.getKey());
  260. sbParams.append("=");
  261. sbParams.append(entry.getValue());
  262. sbParams.append("&");
  263. }
  264. }
  265. HttpURLConnection con = null;
  266. BufferedReader br = null;
  267. try {
  268. URL url = null;
  269. if (sbParams != null && sbParams.length() > 0) {
  270. url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
  271. } else {
  272. url = new URL(urlParam);
  273. }
  274. con = (HttpURLConnection) url.openConnection();
  275. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  276. con.connect();
  277. resultBuffer = new StringBuffer();
  278. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  279. String temp;
  280. while ((temp = br.readLine()) != null) {
  281. resultBuffer.append(temp);
  282. }
  283. } catch (Exception e) {
  284. throw new RuntimeException(e);
  285. } finally {
  286. if (br != null) {
  287. try {
  288. br.close();
  289. } catch (IOException e) {
  290. br = null;
  291. throw new RuntimeException(e);
  292. } finally {
  293. if (con != null) {
  294. con.disconnect();
  295. con = null;
  296. }
  297. }
  298. }
  299. }
  300. return resultBuffer.toString();
  301. }
  302. /**
  303. * @Description:使用URLConnection发送get请求
  304. * @author:liuyc
  305. * @time:2016年5月17日 下午3:27:58
  306. */
  307. public static String sendGet2(String urlParam, Map<String, Object> params, String charset) {
  308. StringBuffer resultBuffer = null;
  309. // 构建请求参数
  310. StringBuffer sbParams = new StringBuffer();
  311. if (params != null && params.size() > 0) {
  312. for (Entry<String, Object> entry : params.entrySet()) {
  313. sbParams.append(entry.getKey());
  314. sbParams.append("=");
  315. sbParams.append(entry.getValue());
  316. sbParams.append("&");
  317. }
  318. }
  319. BufferedReader br = null;
  320. try {
  321. URL url = null;
  322. if (sbParams != null && sbParams.length() > 0) {
  323. url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
  324. } else {
  325. url = new URL(urlParam);
  326. }
  327. URLConnection con = url.openConnection();
  328. // 设置请求属性
  329. con.setRequestProperty("accept", "*/*");
  330. con.setRequestProperty("connection", "Keep-Alive");
  331. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  332. con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  333. // 建立连接
  334. con.connect();
  335. resultBuffer = new StringBuffer();
  336. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  337. String temp;
  338. while ((temp = br.readLine()) != null) {
  339. resultBuffer.append(temp);
  340. }
  341. } catch (Exception e) {
  342. throw new RuntimeException(e);
  343. } finally {
  344. if (br != null) {
  345. try {
  346. br.close();
  347. } catch (IOException e) {
  348. br = null;
  349. throw new RuntimeException(e);
  350. }
  351. }
  352. }
  353. return resultBuffer.toString();
  354. }
  355. /**
  356. * @Description:使用HttpClient发送post请求
  357. * @author:liuyc
  358. * @time:2016年5月17日 下午3:28:23
  359. */
  360. public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
  361. StringBuffer resultBuffer = null;
  362. HttpClient client = new DefaultHttpClient();
  363. HttpPost httpPost = new HttpPost(urlParam);
  364. // 构建请求参数
  365. List<NameValuePair> list = new ArrayList<NameValuePair>();
  366. Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
  367. while (iterator.hasNext()) {
  368. Entry<String, Object> elem = iterator.next();
  369. list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
  370. }
  371. BufferedReader br = null;
  372. try {
  373. if (list.size() > 0) {
  374. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
  375. httpPost.setEntity(entity);
  376. }
  377. HttpResponse response = client.execute(httpPost);
  378. // 读取服务器响应数据
  379. resultBuffer = new StringBuffer();
  380. br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  381. String temp;
  382. while ((temp = br.readLine()) != null) {
  383. resultBuffer.append(temp);
  384. }
  385. } catch (Exception e) {
  386. throw new RuntimeException(e);
  387. } finally {
  388. if (br != null) {
  389. try {
  390. br.close();
  391. } catch (IOException e) {
  392. br = null;
  393. throw new RuntimeException(e);
  394. }
  395. }
  396. }
  397. return resultBuffer.toString();
  398. }
  399. /**
  400. * @Description:使用HttpClient发送get请求
  401. * @author:liuyc
  402. * @time:2016年5月17日 下午3:28:56
  403. */
  404. public static String httpClientGet(String urlParam, Map<String, Object> params, String charset) {
  405. StringBuffer resultBuffer = null;
  406. HttpClient client = new DefaultHttpClient();
  407. BufferedReader br = null;
  408. // 构建请求参数
  409. StringBuffer sbParams = new StringBuffer();
  410. if (params != null && params.size() > 0) {
  411. for (Entry<String, Object> entry : params.entrySet()) {
  412. sbParams.append(entry.getKey());
  413. sbParams.append("=");
  414. try {
  415. sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
  416. } catch (UnsupportedEncodingException e) {
  417. throw new RuntimeException(e);
  418. }
  419. sbParams.append("&");
  420. }
  421. }
  422. if (sbParams != null && sbParams.length() > 0) {
  423. urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
  424. }
  425. HttpGet httpGet = new HttpGet(urlParam);
  426. try {
  427. HttpResponse response = client.execute(httpGet);
  428. // 读取服务器响应数据
  429. br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  430. String temp;
  431. resultBuffer = new StringBuffer();
  432. while ((temp = br.readLine()) != null) {
  433. resultBuffer.append(temp);
  434. }
  435. } catch (Exception e) {
  436. throw new RuntimeException(e);
  437. } finally {
  438. if (br != null) {
  439. try {
  440. br.close();
  441. } catch (IOException e) {
  442. br = null;
  443. throw new RuntimeException(e);
  444. }
  445. }
  446. }
  447. return resultBuffer.toString();
  448. }
  449. /**
  450. * @Description:使用socket发送post请求
  451. * @author:liuyc
  452. * @time:2016年5月18日 上午9:26:22
  453. */
  454. public static String sendSocketPost(String urlParam, Map<String, Object> params, String charset) {
  455. String result = "";
  456. // 构建请求参数
  457. StringBuffer sbParams = new StringBuffer();
  458. if (params != null && params.size() > 0) {
  459. for (Entry<String, Object> entry : params.entrySet()) {
  460. sbParams.append(entry.getKey());
  461. sbParams.append("=");
  462. sbParams.append(entry.getValue());
  463. sbParams.append("&");
  464. }
  465. }
  466. Socket socket = null;
  467. OutputStreamWriter osw = null;
  468. InputStream is = null;
  469. try {
  470. URL url = new URL(urlParam);
  471. String host = url.getHost();
  472. int port = url.getPort();
  473. if (-1 == port) {
  474. port = 80;
  475. }
  476. String path = url.getPath();
  477. socket = new Socket(host, port);
  478. StringBuffer sb = new StringBuffer();
  479. sb.append("POST " + path + " HTTP/1.1\r\n");
  480. sb.append("Host: " + host + "\r\n");
  481. sb.append("Connection: Keep-Alive\r\n");
  482. sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
  483. sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
  484. // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
  485. sb.append("\r\n");
  486. if (sbParams != null && sbParams.length() > 0) {
  487. sb.append(sbParams.substring(0, sbParams.length() - 1));
  488. }
  489. osw = new OutputStreamWriter(socket.getOutputStream());
  490. osw.write(sb.toString());
  491. osw.flush();
  492. is = socket.getInputStream();
  493. String line = null;
  494. // 服务器响应体数据长度
  495. int contentLength = 0;
  496. // 读取http响应头部信息
  497. do {
  498. line = readLine(is, 0, charset);
  499. if (line.startsWith("Content-Length")) {
  500. // 拿到响应体内容长度
  501. contentLength = Integer.parseInt(line.split(":")[1].trim());
  502. }
  503. // 如果遇到了一个单独的回车换行,则表示请求头结束
  504. } while (!line.equals("\r\n"));
  505. // 读取出响应体数据(就是你要的数据)
  506. result = readLine(is, contentLength, charset);
  507. } catch (Exception e) {
  508. throw new RuntimeException(e);
  509. } finally {
  510. if (osw != null) {
  511. try {
  512. osw.close();
  513. } catch (IOException e) {
  514. osw = null;
  515. throw new RuntimeException(e);
  516. } finally {
  517. if (socket != null) {
  518. try {
  519. socket.close();
  520. } catch (IOException e) {
  521. socket = null;
  522. throw new RuntimeException(e);
  523. }
  524. }
  525. }
  526. }
  527. if (is != null) {
  528. try {
  529. is.close();
  530. } catch (IOException e) {
  531. is = null;
  532. throw new RuntimeException(e);
  533. } finally {
  534. if (socket != null) {
  535. try {
  536. socket.close();
  537. } catch (IOException e) {
  538. socket = null;
  539. throw new RuntimeException(e);
  540. }
  541. }
  542. }
  543. }
  544. }
  545. return result;
  546. }
  547. /**
  548. * @Description:使用socket发送get请求
  549. * @author:liuyc
  550. * @time:2016年5月18日 上午9:27:18
  551. */
  552. public static String sendSocketGet(String urlParam, Map<String, Object> params, String charset) {
  553. String result = "";
  554. // 构建请求参数
  555. StringBuffer sbParams = new StringBuffer();
  556. if (params != null && params.size() > 0) {
  557. for (Entry<String, Object> entry : params.entrySet()) {
  558. sbParams.append(entry.getKey());
  559. sbParams.append("=");
  560. sbParams.append(entry.getValue());
  561. sbParams.append("&");
  562. }
  563. }
  564. Socket socket = null;
  565. OutputStreamWriter osw = null;
  566. InputStream is = null;
  567. try {
  568. URL url = new URL(urlParam);
  569. String host = url.getHost();
  570. int port = url.getPort();
  571. if (-1 == port) {
  572. port = 80;
  573. }
  574. String path = url.getPath();
  575. socket = new Socket(host, port);
  576. StringBuffer sb = new StringBuffer();
  577. sb.append("GET " + path + " HTTP/1.1\r\n");
  578. sb.append("Host: " + host + "\r\n");
  579. sb.append("Connection: Keep-Alive\r\n");
  580. sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
  581. sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
  582. // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
  583. sb.append("\r\n");
  584. if (sbParams != null && sbParams.length() > 0) {
  585. sb.append(sbParams.substring(0, sbParams.length() - 1));
  586. }
  587. osw = new OutputStreamWriter(socket.getOutputStream());
  588. osw.write(sb.toString());
  589. osw.flush();
  590. is = socket.getInputStream();
  591. String line = null;
  592. // 服务器响应体数据长度
  593. int contentLength = 0;
  594. // 读取http响应头部信息
  595. do {
  596. line = readLine(is, 0, charset);
  597. if (line.startsWith("Content-Length")) {
  598. // 拿到响应体内容长度
  599. contentLength = Integer.parseInt(line.split(":")[1].trim());
  600. }
  601. // 如果遇到了一个单独的回车换行,则表示请求头结束
  602. } while (!line.equals("\r\n"));
  603. // 读取出响应体数据(就是你要的数据)
  604. result = readLine(is, contentLength, charset);
  605. } catch (Exception e) {
  606. throw new RuntimeException(e);
  607. } finally {
  608. if (osw != null) {
  609. try {
  610. osw.close();
  611. } catch (IOException e) {
  612. osw = null;
  613. throw new RuntimeException(e);
  614. } finally {
  615. if (socket != null) {
  616. try {
  617. socket.close();
  618. } catch (IOException e) {
  619. socket = null;
  620. throw new RuntimeException(e);
  621. }
  622. }
  623. }
  624. }
  625. if (is != null) {
  626. try {
  627. is.close();
  628. } catch (IOException e) {
  629. is = null;
  630. throw new RuntimeException(e);
  631. } finally {
  632. if (socket != null) {
  633. try {
  634. socket.close();
  635. } catch (IOException e) {
  636. socket = null;
  637. throw new RuntimeException(e);
  638. }
  639. }
  640. }
  641. }
  642. }
  643. return result;
  644. }
  645. /**
  646. * @Description:读取一行数据,contentLe内容长度为0时,读取响应头信息,不为0时读正文
  647. * @time:2016年5月17日 下午6:11:07
  648. */
  649. private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
  650. List<Byte> lineByte = new ArrayList<Byte>();
  651. byte tempByte;
  652. int cumsum = 0;
  653. if (contentLength != 0) {
  654. do {
  655. tempByte = (byte) is.read();
  656. lineByte.add(Byte.valueOf(tempByte));
  657. cumsum++;
  658. } while (cumsum < contentLength);// cumsum等于contentLength表示已读完
  659. } else {
  660. do {
  661. tempByte = (byte) is.read();
  662. lineByte.add(Byte.valueOf(tempByte));
  663. } while (tempByte != 10);// 换行符的ascii码值为10
  664. }
  665. byte[] resutlBytes = new byte[lineByte.size()];
  666. for (int i = 0; i < lineByte.size(); i++) {
  667. resutlBytes[i] = (lineByte.get(i)).byteValue();
  668. }
  669. return new String(resutlBytes, charset);
  670. }
  671. }

java 常见几种发送http请求案例的更多相关文章

  1. Ajax发送XML请求案例

    Ajax发送XML请求需求: 根据输入的国家,输出这些国家下面的城市. 如果请求参数较多,而且请求参数的结构关系复杂,则可以考虑发送XML请求.XML请求的实质还是POST请求,只是在发送请求的客户端 ...

  2. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  3. Java利用原始HttpURLConnection发送http请求数据小结

    1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...

  4. java中原生的发送http请求(无任何的jar包导入)

    package com.teamsun.pay.wxpay.util; import java.io.BufferedReader; import java.io.IOException; impor ...

  5. Ajax发送简单请求案例

    所谓简单请求,是指不包含任何参数的请求.这种请求通常用于自动刷新的应用,例如证券交易所的实时信息发送.这种请求通常用于公告性质的响应,公告性质的响应无需客户端的任何请求参数,而是由服务器根据业务数据自 ...

  6. java常见3种文件上传速度对比和文件上传方法详细代码

    在java里面文件上传的方式很多,最简单的依然是FileInputStream.FileOutputStream了,在这里我列举3种常见的文件上传方法代码,并比较他们的上传速度(由于代码是在本地测试, ...

  7. Java之使用HttpClient发送GET请求

    package LoadRunner; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import o ...

  8. java中两种发起POST请求,并接收返回的响应内容的方式  (转)

    http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...

  9. PHP的3种发送HTTP请求的方式

    1.CURL方式发送数据及上传文件 <?php class IndexController extends ControllerBase { public function indexActio ...

随机推荐

  1. e682. 获得打印页的尺寸

    Note that (0, 0) of the Graphics object is at the top-left of the actual page, which is outside the ...

  2. e673. Getting Amount of Free Accelerated Image Memory

    Images in accelerated memory are much faster to draw on the screen. However, accelerated memory is t ...

  3. UVA 1371 - Period(DP)

    题目链接:option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=4117&mo ...

  4. Python 爬虫批量下载美剧 from 人人影视 HR-HDTV

    本人比較喜欢看美剧.尤其喜欢人人影视上HR-HDTV 的 1024 分辨率的高清双字美剧,这里写了一个脚本来批量获得指定美剧的全部 HR-HDTV 的 ed2k下载链接.并依照先后顺序写入到文本文件, ...

  5. eclipse 远程链接访问hadoop 集群日志信息没有输出的问题l

    Eclipse插件Run on Hadoop没有用到hadoop集群节点的问题参考来源 http://f.dataguru.cn/thread-250980-1-1.html http://f.dat ...

  6. [入门阅读]怎样在android中解析JSON

    JSON入门介绍:http://kirin.javaeye.com/blog/616226 也参考了此篇:http://blog.163.com/fushaolin@126/blog/static/1 ...

  7. 如何在word文档中添加mathtype加载项

    MathType是强大的数学公式编辑器,通常与office一起使用,mathtype安装完成后,正常情况下会在word文档中的菜单中自动添加mathtype加载项,但有时也会出现小意外,mathtyp ...

  8. 视觉SLAM之词袋(bag of words) 模型与K-means聚类算法浅析(1)

    在目前实际的视觉SLAM中,闭环检测多采用DBOW2模型https://github.com/dorian3d/DBoW2,而bag of words 又运用了数据挖掘的K-means聚类算法,笔者只 ...

  9. Java输入输出流(2)

    6. Java.IO流类库 1. io流的四个基本类 java.io包中包括了流式I/O所须要的全部类. 在java.io包中有四个基本类:InputStream.OutputStream及Reade ...

  10. POJ 1947 Rebuilding Road(树形DP)

    Description The cows have reconstructed Farmer John's farm, with its N barns (1 <= N <= 150, n ...