[说明]:非原创,前两种post请求需要依赖Apache开源框架来实现;最后一种get/post请求则不需要依赖第三方框架

  • 普通表单调用(post请求)

/**
* 普通表单调用
* 根据参数url,处理post请求,获取远程返回的response,然后返回相对应的ActionResult
*
*/
public ActionResult post(String url, Map<String,String> params){
/**
1.创建httpClient对象
2.创建HttpPost对象
3.设置post请求的实体内容
4.通过HttpPost对象执行post请求,获得response
5.获得response的实体内容(json格式),将实体内容转换成字符串(实际上是json格式的字符串),最后将json字符串转换成ActionResult对象
*/
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for(Map.Entry<String,String> entry : params.entrySet()){ nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); }
try{ post.setEntity(new UrlEncodedFormEntity(nvps,charsetName)); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); return JsonUtils.fromString(EntityUtils.toString(entity,"utf-8"),ActionResult.class); }catch(Exception e){ e.printStackTrace(); return null; }finally{
try{ httpClient.getConnetionManager.shutdown(); }catch(Exception e){
e.printStackTrace();
}
}
}

带文件上传的表单

/**
*带文件上传的表单
*
*/
public ActionResult postWithFile(String url, Map<String,Object> params){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
try{
for(Map.Entry<String, Object> entry : params.entrySet()){
String key = entry.getKey();
Object value = entry.getValue();
if(value instanceof File){
File file = (File)value;
FileBody fileBody = new FileBody(file);
reqEntity.addPart(key,fileBody);
}else{
StringBody stringBody = new StringBody(String.valueOf(value),Charset.forName("utf-8"));
reqEntity.addPart(key, stringBody);
}
}
post.setEntity(reqEntity);
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
return JsonUtils.fromString(EntityUtils.toString(entity,"utf-8"),
ActionResult.class);
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try{
httpClient.getConnetionManager.shutdown();
}catch(Exception e){
e.printStackTrace();
}
}
}

不依赖第三发jar包实现,处理get请求以及普通post请求的方法

/**
*不依赖第三发jar包实现,处理get请求以及普通post请求的方法
*
*/
public String getOrPost(String type, String url, String encoding, String contentType, String params, HttpServletRequest request){
/**
* 1.确定编码和contentType
2.确定url:如果传入url不包含http,则应当重新组装url
3.确定请求参数(GET请求)
4.创建URLConnection对象
5.设置URLConnection对象的属性(请求方式/是否使用缓存/本次连接是否自动处理重定向/UA/Accept/)
如果是post请求,则必须设置DoInput,DoOutput,Content-Type
post请求不能使用缓存(设置http请求头属性)
6.创建真实连接
7.如果是post请求,则设置http请求正文
8.获取远程返回的InputStream,读取InputStream,返回结果
9.关闭流,断开连接
*
*/
encoding = encoding==null ? "utf-8" : encoding; contentType = contentType==null ? "application/x-www-form-urlencoded" : contentType; if(!url.startsWith("http://") && !url.startsWith("https://") && request!=null){
url = getBasePath(request)+url;
} if("GET".equals(type) && notEmtpy(params)){
if(!url.contains("?")){
url+="?"+params;
}else{
url+="&"+params;
}
} HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection(); //设置请求头
conn.setRequestMethod(type);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
conn.setRequestProperty("accept","*/*"); if("POST".equals(type)){
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type",contentType);
} //实际上只是建立了一个与服务器的TCP连接,并没有发送http请求;
//只有在执行conn.getInputStream()时,才真正发送http请求
conn.connect(); //设置请求正文(POST请求)
if("POST".equals(type)){
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),encoding);
out.write(params);
out.flush();
out.close();
} //获取数据
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charset.forName(encoding)));
String str;
StringBuffer sb = new StringBuffer("");
while((str = br.readLine())!= null){
sb.append(str);
}
br.close();
conn.disconnect();
return sb.toString(); }

http请求get与post请求的几种实现的更多相关文章

  1. IIS请求筛选模块被配置为拒绝超过请求内容长度的请求

    HTTP错误404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求,原因是Web服务器上的请求筛选被配置为拒绝该请求,因为内容长度超过配置的值(IIS 7 默认文件上传大 ...

  2. Android okHttp网络请求之Get/Post请求

    前言: 之前项目中一直使用的Xutils开源框架,从xutils 2.1.5版本使用到最近的xutils 3.0,使用起来也是蛮方便的,只不过最近想着完善一下app中使用的开源框架,由于Xutils里 ...

  3. 普通B/S架构模式同步请求与AJAX异步请求区别(个人理解)

    在上次面试的时候有被问到过AJAX同步与异步之间的概念问题,之前没有涉及到异步与同步的知识,所以特意脑补了一下,不是很全面... 同步请求流程:提交请求(POST/GET表单相似的提交操作)---服务 ...

  4. x-requested-with 请求头 区分ajax请求还是普通请求(转)

    在服务器端判断request来自Ajax请求(异步)还是传统请求(同步): 两种请求在请求的Header不同,Ajax 异步请求比传统的同步请求多了一个头参数 1.传统同步请求参数 accept  t ...

  5. HTTP错误404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求

    http://www.cnblogs.com/JKqingxinfeng/archive/2012/10/29/2744663.html HTTP错误404.13 - Not Found 请求筛选模块 ...

  6. zzy:请求静态资源和请求动态资源, src再次请求服务器资源

    [总结可以发起请求的阶段:请求动态资源:通过web.xml匹配action然后,自定义Servlet处理该action1)form表单提交请求的时候,用action设定,该页面发起请求的Servlet ...

  7. HTTP协议---HTTP请求中的常用请求字段和HTTP的响应状态码及响应头

    http://blog.csdn.net/qxs965266509/article/details/8082810 用于HTTP请求中的常用请求头字段 Accept:用于高速服务器,客户机支持的数据类 ...

  8. HTTP 笔记与总结(2 )HTTP 协议的(请求行的)请求方法 及 (响应行的)状态码

    (请求行的)请求方法 包括: GET,POST,HEAD,PUT,TRACE,DELETE,OPTIONS 注意:这些请求方法虽然是 HTTP 协议规定的,但是 Web Server 未必允许或支持这 ...

  9. WebApi接口传参不再困惑(4):传参详解 一、get请求 二、post请求 三、put请求 四、delete请求 五、总结

    前言:还记得刚使用WebApi那会儿,被它的传参机制折腾了好久,查阅了半天资料.如今,使用WebApi也有段时间了,今天就记录下API接口传参的一些方式方法,算是一个笔记,也希望能帮初学者少走弯路.本 ...

随机推荐

  1. MyBatis中关于别名typeAliases的设置

    第一种:通过在配置文件中typeAlias节点设置type的方式 <?xml version="1.0" encoding="UTF-8" ?> & ...

  2. ListView控件--2016年12月9日

    ListView属性 ListView   名称 说明 AccessKey 重写 WebControl.AccessKey 属性. 不支持将此属性设置 ListView 控件.(覆盖 WebContr ...

  3. BZOJ 2079: [Poi2010]Guilds

    Description 问一个图是否有二染色方案,满足每个点都跟他颜色不用的点有连边. Sol 结论题. 除了只有一个点,否则任何图都能被二染色. Code /******************** ...

  4. css3渐变

    background:-webkit-linear-gradient | radial-gradient (水平起点 垂直起点 , 颜色1  百分比%, 颜色2  百分比%, ... ,颜色N 100 ...

  5. [转载]js中return的用法

    一.返回控制与函数结果,语法为:return 表达式; 语句结束函数执行,返回调用函数,而且把表达式的值作为函数的结果 二.返回控制,无函数结果,语法为:return;  在大多数情况下,为事件处理函 ...

  6. 【ASP.NET】VS编译成功后自动生成Nuget包

    在VisualStudio项目中,可以在每次编译成功后自动发布nuget包,具体配置过程如下:   1.下载nuget.exe,放置在Visual Studio项目的根目录下.   2.通过命令行生成 ...

  7. windows 安装 mongodb

    windows 安装 mongodb 下载 首先到官网下载合适的安装包,下载地址为 https://www.mongodb.com/download-center MongoDB for Window ...

  8. 442. Find All Duplicates in an Array

    https://leetcode.com/problems/find-all-duplicates-in-an-array/ 一列数,1 ≤ a[i] ≤ n (n = size of array), ...

  9. asp.net mvc ajax FileUpload

    //后台代码 [HttpPost] public ActionResult CreateCategory(HttpPostedFileBase file) { string url = Upload( ...

  10. Android安全攻防战,反编译与混淆技术完全解析(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/49738023 之前一直有犹豫过要不要写这篇文章,毕竟去反编译人家的程序并不是什么值 ...