HttpURLConnection使用

来源:互联网 发布:淘宝详情免费模板代码 编辑:程序博客网 时间:2024/06/04 18:39

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
原创粉丝点击