[说明]:非原创,前两种post请求需要依赖Apache开源框架来实现;最后一种get/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请求的方法 * */ 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://www.cnblogs.com/pengmeilun/p/5107593.html