http远程访问工具类

mport java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @author liucy
 * http远程访问
 */
public class HttpURLUtil {
private static final String SERVLET_POST = "POST";  

//读取超时 默认10秒
private static final int READ_TIMEOUT = 10000;
//连接超时 默认10秒
private static final int CONNECT_TIMEOUT = 10000;

/**
* http远程访问
* @param httpUrl HTTP请求URL 
* @param argument HTTP请求的参数
* @return HTTP响应的返回数据
* @throws IOException
*/
public static String doPost(String httpUrl, String argument) 
throws IOException{
//构造一个URL对象
URL url = new URL(httpUrl);
String returnStr = null;
HttpURLConnection urlConn = null;
DataOutputStream out = null;

try{
//使用HttpURLConnection打开连接  
   urlConn = (HttpURLConnection) url.openConnection();    
   //初始化配置
   initURLConn(urlConn);
   // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
   // 要注意的是connection.getOutputStream会隐含的进行connect。  
   urlConn.connect();
   //DataOutputStream写入流
   out = new DataOutputStream(urlConn.getOutputStream());
   //要上传的参数 
   if(argument != null)
    out.write(argument.getBytes("UTF-8"));
   //刷新、关闭 
   out.flush();
   out.close();
   
   //数据接收,获取数据
   returnStr = BufStreamUtil.readStrStream(urlConn.getInputStream());
}finally{
if(out != null)
out.close();
//关闭http连接
if(urlConn != null)
urlConn.disconnect();
}

return returnStr;
}

/**
* 初始化配置
* @param urlConn
* @throws IOException
*/
private static void initURLConn(HttpURLConnection urlConn) throws IOException{
//读取超时
   urlConn.setReadTimeout(READ_TIMEOUT);
   //连接超时
   urlConn.setConnectTimeout(CONNECT_TIMEOUT);
   //因为这个是post请求,设立需要设置为true  
   urlConn.setDoOutput(true);  
   urlConn.setDoInput(true);  
   //设置以POST方式  
   urlConn.setRequestMethod(SERVLET_POST);
   // Post 请求不能使用缓存  
   urlConn.setUseCaches(false);  
   urlConn.setInstanceFollowRedirects(true);  
   // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
   urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
}

}


测试类:

import java.io.IOException;


public class HttpTest {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
String httpUrl = "https://www.chengxindai.com/wdzj/api/interface/getProjectsByDate.html";
String argument = "date="+"2014-05-01";
String str = HttpURLUtil.doPost(httpUrl, argument);
System.out.println("################## httpStrServlet 响应: " + str);
}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值