zoukankan      html  css  js  c++  java
  • 使用HttpURLConnection向服务器发送post和get请求(转)

    一、使用HttpURLConnection向服务器发送get请求

    1、向服务器发送get请求

    复制代码
        @Test
    publicvoid sendSms() throws Exception{
    String message="货已发到";
    message=URLEncoder.encode(message, "UTF-8");
    System.out.println(message);
    String path ="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
    URL url =new URL(path);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setConnectTimeout(5*1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    byte[] data = StreamTool.readInputStream(inStream);
    String result=new String(data, "UTF-8");
    System.out.println(result);
    }
    复制代码

    2、从服务器读取数据    

    String message=request.getParameter("message");

                

                   

    二、使用HttpURLConnection向服务器发送post请求

    1、向服务器发送post请求

    复制代码
        @Test
    publicvoid addByUrl() throws Exception{
    String encoding="UTF-8";
    String params="[{"addTime":"2011-09-19 14:23:02"[],"iccid":"1111","id":0,"imei":"2222","imsi":"3333","phoneType":"4444","remark":"aaaa","tel":"5555"}]";
    String path ="http://localhost:8083/xxxx/xxx/sim!add.do";
    byte[] data = params.getBytes(encoding);
    URL url =new URL(path);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
    conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    conn.setConnectTimeout(5*1000);
    OutputStream outStream = conn.getOutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();
    System.out.println(conn.getResponseCode()); //响应代码 200表示成功
    if(conn.getResponseCode()==200){
    InputStream inStream = conn.getInputStream();  
    String result=new String(StreamTool.readInputStream(inStream), "UTF-8");
    }
    }
    复制代码

                    

    2、从服务器读取数据   

    //获取post请求过来的数据
    byte[] data=StreamTool.readInputStream(request.getInputStream());
    //[{"addTime":"2011-09-19 14:23:02"[],"iccid":"1111","id":0,"imei":"2222","imsi":"3333","phoneType":"4444","remark":"aaaa","tel":"5555"}]
    String json=new String(data, "UTF-8");

    http://www.cnblogs.com/linjiqin/archive/2011/09/19/2181634.html

  • 相关阅读:
    两道关于算法的面试题
    MySQL连接数过多程序报错"too many connections"
    Mysql中类似于Oracle中connect by ... start with的查询语句(木大看懂)
    获取当前div中的文本(只获取当前div的, 子元素不要, 基于layui)
    同一张地区表中根据汉字查询地区的代码
    HttpURLConnection getInputStream异常的解决
    IDEA报错No Spring WebApplicationInitializer types detected on classpath
    mybatis出现无效的列类型
    hibernate NUMBER 精度
    jmeter汉化或英化
  • 原文地址:https://www.cnblogs.com/softidea/p/4809252.html
Copyright © 2011-2022 走看看