示例代码:

package com.shareboxes.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.junit.Ignore;
import org.junit.Test; /**
* @ClassName: HttpRequest
* @Description: get,post请求
* @author Administrator
* @date 2015年10月19日
*
*/ public class HttpRequest { /**
* @Title: sendGet
* @Description: get请求
* @param url
* @param param
*/
public static String sendGet(String url, Map<String, String> param) {
BufferedReader bReader = null;
StringBuffer sBuffer = new StringBuffer();
String realUrl = url; try { if (param.size() > 0) {
realUrl += "?";
for (Entry<String, String> entry : param.entrySet()) {
realUrl += entry.getKey() + "=" + entry.getValue() + "&";
}
realUrl = realUrl.substring(0, realUrl.length() - 1);
} URL urlString = new URL(realUrl);
URLConnection urlConnection = urlString.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setRequestMethod("GET");// 设置请求方法
httpURLConnection.setConnectTimeout(30000);// 连接主机超时时间
httpURLConnection.setReadTimeout(30000);// 读取数据超时时间
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置请求数据的格式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");// 设置接收数据的编码 // 判断连接是否异常
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} System.out.println(httpURLConnection.getResponseCode());
for(Entry<String, List<String>>entry:httpURLConnection.getHeaderFields().entrySet()){
System.out.println(entry.getKey()+"--------->"+entry.getValue());
} bReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = bReader.readLine()) != null) {
sBuffer.append(line);
}
} catch (Exception e) {
System.out.println("get 请求发生错误!!!");
e.printStackTrace();
} finally {
if (bReader != null) {
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sBuffer.toString();
} /**
* @Title: sendPost
* @Description: post请求
* @param url
* @param param
*/
public static String sendPost(String url, Map<String, String> param) {
BufferedReader bReader = null;
OutputStreamWriter out = null;
StringBuffer sBuffer = new StringBuffer();
String parameterData =""; try {
if (param.size() > 0) {
for (Entry<String, String> entry : param.entrySet()) {
parameterData += entry.getKey() + "=" + entry.getValue() + "&";
}
parameterData = parameterData.substring(0, parameterData.length() - 1);
} URL realUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection(); httpURLConnection.setConnectTimeout(30000);
httpURLConnection.setReadTimeout(30000);
httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setInstanceFollowRedirects(true); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置请求参数的格式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");// 接收数据的编码 if((parameterData.trim().length()>0) && (!parameterData.equals(""))){
out = new OutputStreamWriter(httpURLConnection.getOutputStream(), "utf-8");
out.write(parameterData);
out.flush();
} // 判断连接是否异常
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} System.out.println(httpURLConnection.getResponseCode());
for(Entry<String, List<String>>entry:httpURLConnection.getHeaderFields().entrySet()){
System.out.println(entry.getKey()+"--------->"+entry.getValue());
} // bReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
// String line = null;
// while ((line = bReader.readLine()) != null) {
// sBuffer.append(line);
// } InputStream in=httpURLConnection.getInputStream();
byte []data=new byte[httpURLConnection.getContentLength()];
int offset=0;
while(offset<in.available()){
offset+=in.read(data, offset, in.available()-offset);
System.out.println(offset);
}
sBuffer.append(new String(data,"utf-8"));
} catch (Exception e) {
System.out.println("post 请求失败!!!");
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (bReader != null) {
bReader.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return sBuffer.toString();
} @Test
@Ignore
public void testGet() {
Map<String, String> param = new HashMap<String, String>();
param.put("tid", "1");
System.out.println(sendGet("http://localhost:8080/shareboxes/record/getrecord/tid.do", param));
} @Test
public void testPost() {
Map<String, String> param = new HashMap<String, String>();
param.put("tid", "1");
System.out.println(sendPost("http://localhost:8080/shareboxes/record/getrecord/tid.do", param));
} }

最新文章

  1. 4.MySQL 主主(m-m) 同步生产库标准同步操作实施流程
  2. iOS开发常用代码块(第二弹)
  3. 【csuoj1014】 西湖三人行
  4. 从表中删除重复记录的sql
  5. LeetCode 4 Median of Two Sorted Arrays (两个数组的mid值)
  6. 编写高质量代码改善C#程序的157个建议[正确操作字符串、使用默认转型方法、却别对待强制转换与as和is]
  7. C#分部方法
  8. string和stringBuilder区别
  9. 编译mgiza的准备
  10. Word2003使用VBA教程
  11. javascript 引擎Rhino源代码分析 浅析 实例函数对象及this
  12. gzip [选项] 压缩(解压缩)
  13. 关于datagridview单元格不切换焦点无法获得新输入数据的问题解决方法
  14. 转载:C#实现接口回调
  15. 【3】python核心编程 第五章-数字
  16. ubuntu修改grub,修改开机顺序,配置grub启动顺序
  17. jQuery实现移动端评测问卷功能
  18. CodeChef Little Elephant and Mouses [DP]
  19. linux dns搭建
  20. 如何创建 SVN 服务器,并搭建自己的 SVN 仓库 如何将代码工程添加到VisualSVN Server里面管理

热门文章

  1. Difference between Tomcat&#39;s extraResourcePaths and aliases to access an external directory--转
  2. Linux用户磁盘配额
  3. centos5.5上apache快速安装H264流媒体支持MP4-H264边下边播
  4. VB中的Dictionary对象
  5. bootstrap初探
  6. (转)PHP 的 __FILE__ 常量
  7. Android开发手记(12) Menu的使用
  8. CodeSMART for VS.NET插件工具
  9. Objective-C学习篇10—NSDate与NSDateFormatter
  10. Something About Variable