HttpURLConnection使用

1:实际使用(GET)

HttpURLConnection conn;
String targetUrl = urlAddr + "?appid=" +appid;//后面跟的参数名
if (Config.isSaveStreamingPos() && autoPersist.loadPos()!=null){
    targetUrl = targetUrl + "&loc=" + autoPersist.loadPos();
}
try {
    URL url = new URL(targetUrl);
    conn = (HttpURLConnection)url.openConnection();
    conn.setConnectTimeout(1000);//超时设置,防止 网络异常的情况下,可能会导致程序僵死而不继续往下执行
    conn.setReadTimeout(1000);//超时设置,防止 网络异常的情况下,可能会导致程序僵死而不继续往下执行
    conn.setRequestMethod("GET");//GETLEIXIN
    for (String key : connParams.getHeaders().keySet()){
        String val = connParams.getHeaders().get(key);
        conn.setRequestProperty(key, val);//
 
 
  1. // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)    
  2. // httpUrlConnection.setRequestProperty("Content-type""application/x-java-serialized-object");    
} try { conn.connect(); } catch (Exception e) { throw new StreamingException("stream url connect failed", e); }
int statusCode = conn.getResponseCode();
DataInputStream in;
in = new DataInputStream(conn.getInputStream());

2:实际使用(POST)

OutputStream os = httpConn.getOutputStream();    
             String param = new String();    
             param = "CorpID=" + CorpID +    
                     "&LoginName=" + LoginName+    
                     "&send_no=" + phoneNumber +    
                     "&msg=" + java.net.URLEncoder.encode(msg,"GBK"); ;    
             os.write(param.getBytes());    

传递参数;

写序列化数据:

// 现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。    
ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm);    
     
// 向对象输出流写出数据,这些数据将存到内存缓冲区中    
objOutputStrm.writeObject(new String("我是测试数据"));    
     
// 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)    
objOutputStm.flush();    
    
// 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,    
// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器    
objOutputStm.close();  



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值