Java post 请求
2015-08-13 14:46
751 查看
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.PostMethod; public class Dopost { public String callHttpPost(String url,NameValuePair[] postData){ HttpClient httpclient = new HttpClient(); PostMethod postMethod = new PostMethod(url); try{ postMethod.addParameters(postData); postMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); int statusCode = httpclient.executeMethod(postMethod); if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){ Header locationHeader = postMethod.getResponseHeader("Location"); String location = null; if(locationHeader != null){ location = locationHeader.getValue(); } postMethod = new PostMethod(location); postMethod.setRequestBody(postData); postMethod.getParams().setParameter("http.protocol.cookie-policy",CookiePolicy.BROWSER_COMPATIBILITY); int statusCode1 = httpclient.executeMethod(postMethod); if(statusCode1 != HttpStatus.SC_OK){ return "postError01:重定向访问没有成功!"; } } if(statusCode != HttpStatus.SC_OK){ return "postError02:访问没有成功!"; } InputStream responseBody = postMethod.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody,"utf-8")); String line = reader.readLine(); String repose=""; while(line != null){ repose+=new String(line.getBytes()); line = reader.readLine(); } return repose; } catch (HttpException e) { return "postError03:"+e; } catch (IOException e) { return "postError04:"+e; }finally{ postMethod.releaseConnection(); } } }
相关文章推荐
- eclipse studio 使用
- struts2 中chain、redirect、redirectaction的区别
- java基础知识实例
- Spring_Transactional_Propagation
- java入门--4110:圣诞老人的礼物-Santa Clau’s Gifts
- java jaxb
- spring事务定义中,@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) 这样定义有问题吗?
- Java设计模式之抽象工厂模式
- java.lang.OutOfMemoryError: Java heap space
- java设计模式图
- java设计模式----装饰模式
- java 垃圾回收
- java实现的数据库管理类(mysql)
- springMVC
- RSA加密解密及数字签名Java实现
- 在Myeclipse中的动态web工程如何加入struts配置文件
- mybatis整合spring 之 基于接口映射的多对一关系
- Java web学习笔记一:JSP学习
- Android 开发环境配置图文教程(jdk+eclipse+android sdk)
- Java基本数据类型