zoukankan      html  css  js  c++  java
  • android19

    【向Internet发送请求参数】

    利用HttpURLConnection对象,我们可以向网络发送请求参数.
    String requestUrl = "http://192.168.17.9:8080/and/listservlet";
    Map<String, String> requestParams = new HashMap<String, String>();
    requestParams.put("age", "12");
    requestParams.put("name", "中国");
     StringBuilder params = new StringBuilder();
    for(Map.Entry<String, String> entry : requestParams.entrySet()){
     params.append(entry.getKey());
     params.append("=");
     params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
     params.append("&");
    }
    if (params.length() > 0) params.deleteCharAt(params.length() - 1);
    byte[] data = params.toString().getBytes();
    URL realUrl = new URL(requestUrl);
    HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
    conn.setDoOutput(true);//发送POST请求必须设置允许输出
    conn.setUseCaches(false);//不使用Cache
    conn.setRequestMethod("POST");        
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(data);
    outStream.flush();
    if( conn.getResponseCode() == 200 ){
            String result = readAsString(conn.getInputStream(), "UTF-8");
            outStream.close();
            System.out.println(result);
    }

    //---------------------------

    利用HttpURLConnection对象,我们可以向网络发送xml数据.
    StringBuilder xml =  new StringBuilder();
    xml.append("<?xml version="1.0" encoding="utf-8" ?>");
    xml.append("<M1 V=10000>");
    xml.append("<U I=1 D="N73">中国</U>");
    xml.append("</M1>");
    byte[] xmlbyte = xml.toString().getBytes("UTF-8");
    URL url = new URL("http://192.168.17.9:8080/and/listservlet");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5* 1000);
    conn.setDoOutput(true);//允许输出
    conn.setUseCaches(false);//不使用Cache
    conn.setRequestMethod("POST");        
    conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
    conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(xmlbyte);//发送xml数据
    outStream.flush();
    if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
    InputStream is = conn.getInputStream();//获取返回数据
    String result = readAsString(is, "UTF-8");
    outStream.close(); 

    //---------------------------------------------------

  • 相关阅读:
    hdu1698(线段树)
    poj3468(线段树)
    hdu1394(线段树求逆序对)
    hdu1754(线段树)
    hdu1166(线段树)
    hdu2412(树形dp)
    hdu4714(树形dp)
    hdu4705(树形dp)
    hdu4679(树形dp)
    滑动导航条
  • 原文地址:https://www.cnblogs.com/Miami/p/3139344.html
Copyright © 2011-2022 走看看