JAVA 调用HTTP接口POST或GET实现方式
2016-04-12 17:54
716 查看
package com.yoodb.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpConnectUtil { private static String DUOSHUO_SHORTNAME = "yoodb";//多说短域名 ****.yoodb.**** private static String DUOSHUO_SECRET = "xxxxxxxxxxxxxxxxx";//多说秘钥 /** * get方式 * @param url * @author www.yoodb.com * @return */ public static String getHttp(String url) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler()); try { httpClient.executeMethod(getMethod); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = getMethod.getResponseBodyAsStream(); int len = 0; byte[] buf = new byte[1024]; while((len=in.read(buf))!=-1){ out.write(buf, 0, len); } responseMsg = out.toString("UTF-8"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //释放连接 getMethod.releaseConnection(); } return responseMsg; } /** * post方式 * @param url * @param code * @param type * @author www.yoodb.com * @return */ public static String postHttp(String url,String code,String type) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); httpClient.getParams().setContentCharset("GBK"); PostMethod postMethod = new PostMethod(url); postMethod.addParameter(type, code); postMethod.addParameter("client_id", DUOSHUO_SHORTNAME); postMethod.addParameter("client_secret", DUOSHUO_SECRET); try { httpClient.executeMethod(postMethod); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = postMethod.getResponseBodyAsStream(); int len = 0; byte[] buf = new byte[1024]; while((len=in.read(buf))!=-1){ out.write(buf, 0, len); } responseMsg = out.toString("UTF-8"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection(); } return responseMsg; } }
相关文章推荐
- TCP/IP(六)UDP
- 网络包抓取开发包 Npcap
- 使用libevent编写高并发HTTP server
- TCP/IP(五)IP选路和动态选路
- tomcat http Basic 认证
- iOS RSA的网络安全模型,iOS签名机制总结(登录,token安全,签名)
- 用CornerStone配置SVN,HTTP及svn简单使用说明
- bug:解决httpie测试出现 no module named _cursors
- 一个java网络编程Socket的例子,实现Server与Client聊天
- 【ifconfig】查看当前网络配置信息
- HTTPS背后的加密算法
- Unix网络编程一、二章笔记
- IOCP完成端口模型
- HTTP响应头和请求头信息对照表,以及各种必备对照表
- tcpcopy
- TCP/IP、SOAP、HTTP的区别
- 偷天换日:网络劫持,网页js被伪装替换。
- Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口
- netstat使用详解
- 网络:GET 的使用