HttpURLConnection的基本用法

来源:互联网 发布:重大网络教育学院官网 编辑:程序博客网 时间:2024/05/22 06:26

代码如下:

 //开启子线程发起网络请求        new Thread(new Runnable() {            @Override            public void run() {                try {                    //请求实体的内容转化为byte数组                    final byte[] xmlbyte = strXml.getBytes("UTF-8");                    //初始化连接                    URL url = new URL("http://192.168.1.158:8581/Service");                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    //设置连接的属性                    conn.setConnectTimeout(5000);                    conn.setReadTimeout(5000);                    conn.setDoOutput(true);// 允许输出                    conn.setDoInput(true);                    conn.setUseCaches(false);// 不使用缓存                    conn.setRequestMethod("POST");//设置请求类型                    //设置若干消息头的部分内容。这个是告诉服务器你的客户端的配置/需求。你啥都不告诉,服务器就按缺省配置传递内容给你的客户端                    conn.setRequestProperty("Connection", "close");// 不维持长连接                    conn.setRequestProperty("Charset", "UTF-8");                    conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));                    conn.setRequestProperty("Content-Type", "text/xml");                    conn.setRequestProperty("SOAPAction", "http://localhost:8001/DataService/postOperation" );                    //设置请求实体                    conn.getOutputStream().write(xmlbyte);                    conn.getOutputStream().flush();                    conn.getOutputStream().close();                    // 开始连接,并获取返回码                    int responseCode = conn.getResponseCode();                    //当返回错误的状态码时,200是正常的,其他的都是错的                    if (responseCode != 200) {                        //可以写自己的处理方式。并且流程可以到此就结束了,因为没有返回的数据再供你处理                        // ...(你自己的处理方式)                    }                    //如果返回的状态码是正确的, 获取返回数据                    InputStream is = conn.getInputStream();                    // 使用输出流来输出字符,获取响应实体字符串(string)                    ByteArrayOutputStream out = new ByteArrayOutputStream();                    byte[] buf = new byte[1024];                    int len;                    while ((len = is.read(buf)) != -1) {                        out.write(buf, 0, len);                    }                    String string = out.toString("UTF-8");                    out.close();                    //处理响应实体字符串(string)                    //...(你自己的处理方式)                    //当网络连接出现问题时                } catch (ConnectException e) {                    e.printStackTrace();                    //当网络连接超时时                } catch (SocketTimeoutException e) {                    e.printStackTrace();                    //当IO出现问题时                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();

抓包软件抓取的请求数据包如下图:
这里写图片描述

0 0
原创粉丝点击