使用GET和POST方式将数据提交给服务器

经常需要将数据提交给web服务器,将相关功能封装成了相关的工具方法以便于以后使用:

1、GET方式

    /**
     * 发送GET请求
     * @param path 请求路径
     * @param params 请求参数
     * @param encoding 编码
     * @return response的读取流,请求失败,返回null
     */
    public static InputStream sendGETRequest(String path, Map<String, String> params, String ecoding) throws Exception{
        // http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90
        StringBuilder url = new StringBuilder(path);
        url.append("?");
        for(Map.Entry<String, String> entry : params.entrySet()){
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), ecoding));
            url.append("&");
        }
        url.deleteCharAt(url.length() - 1);
        HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            return conn.getInputStream();
        }
        return null;
    }

2、POST方式

    /**
     * 发送Post请求
     * @param path 请求路径
     * @param params 请求参数
     * @param encoding 编码
     * @return response的读取流,请求失败,返回null
     */
    public static InputStream sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
        //title=liming&timelength=90
        StringBuilder data = new StringBuilder();
        if(params!=null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()){
                data.append(entry.getKey()).append("=");
                data.append(URLEncoder.encode(entry.getValue(), encoding));
                data.append("&");
            }
            data.deleteCharAt(data.length() - 1);
        }
        byte[] entity = data.toString().getBytes();//生成实体数据
        HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);//允许对外输出数据
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(entity);
        if(conn.getResponseCode() == 200){
            return conn.getInputStream();
        }
        return null;
    }


3、通过HttpClient发送Post请求

   /**
     * 通过HttpClient发送Post请求
     * @param path 请求路径
     * @param params 请求参数
     * @param encoding 编码
     * @return response的读取流,请求失败,返回null
     */
    public static InputStream sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数
        if(params!=null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()){
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);
        HttpPost httpPost = new HttpPost(path);
        httpPost.setEntity(entity);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == 200){
            return response.getEntity().getContent();
        }
        return null;
    }


4、向webservice服务器使用post方式提交xml数据

    /**
     * 向webservice服务器使用post方式提交xml数据
     * url : http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx
     * entityData : soap协议:基于xml格式数据的二进制表示
     * contentType :http协议头字段  如:"application/soap+xml; charset=utf-8"
     * 返回值:服务器返回数据的读取流,请求失败,返回null
     */
    public static InputStream postEntityData(String url,byte[] entityData,String contentType) throws Exception{
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Content-Length", String.valueOf(entityData.length));
        conn.getOutputStream().write(entityData);
        if(conn.getResponseCode() == 200){
            return conn.getInputStream();
        }
        return null;
    } 

5、经常需要从一个InputStream中读取数据,在此也抽取成一个方法:

    /**
     * 从流中读取数据
     * @param inStream
     * @return 二进制数据
     */
    public static byte[] readFromInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inStream.close();
        return outputStream.toByteArray();
    }


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值