post请求xml参数的方法

来源:互联网 发布:最好的日语翻译软件 编辑:程序博客网 时间:2024/06/06 07:19

一般post发送请求,参数都是键值对的形式,但是如果请求参数是以xml形式的话,是没有键的。请求方法如下:

httppost.setEntity(new StringEntity("<buffalo-call>\n" +                    "<method>getPhsSmsCode</method>\n" +                    "<map>\n" +                    "<type>java.util.HashMap</type>\n" +                    "<string>PHONENUM</string>\n" +                    "<string>12345678910</string>\n" +                    "<string>PRODUCTID</string>\n" +                    "<string>50</string>\n" +                    "<string>CITYCODE</string>\n" +                    "<string>0817</string>\n" +                    "</map>\n" +                    "\n" +                    "</buffalo-call>", "text/xml"));

发送post请求的例子:

public static String postUrl(CloseableHttpClient httpClient, String url, String[][] params, String xmlParam, String[][] headers){        String ret = null;        // 创建httppost        HttpPost httppost = new HttpPost(url);        // 设置请求头信息        if (headers != null) {            for (int i=0;i<headers.length;i++) {                httppost.addHeader(headers[i][0], headers[i][1]);            }        }        // 创建参数队列        List<NameValuePair> formparams = new ArrayList<NameValuePair>();        for (int i=0;i<params.length;i++){            formparams.add(new BasicNameValuePair(params[i][0], params[i][1]));        }        UrlEncodedFormEntity uefEntity;        try {            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");            httppost.setEntity(uefEntity);            //以xml方式提交参数            if (xmlParam != null) {                httppost.setEntity(new StringEntity(xmlParam, "text/xml"));            }            System.out.println("executing request " + httppost.getURI());            CloseableHttpResponse response = httpClient.execute(httppost);            try {                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                    HttpEntity entity = response.getEntity();                    ret = EntityUtils.toString(entity, "UTF-8");                }            } finally {                response.close();            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            // 关闭连接,释放资源//            try {//                httpClient.close();//            } catch (IOException e) {//                e.printStackTrace();//            }        }        return ret;    }


0 0