string.format在http post请求和响应中抛出异常

时间:2014-03-06 08:20:57

标签: java web-services tomcat

我想有一个方法来放置格式说明符(比如%s)而不是放置硬代码值,你可以在下面找到我的代码;

String userName = "Nicole";
    String password = "Nicole";

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost("url");

    String input=String.format("<soap:Envelope 

    xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:inn=\"http:Innovation/\">

    <soap:Header/><soap:Body><inn:getCategoriesbyVendorID><!--Optional:-->

    <userName>%s</userName><!--Optional:--><password>%s</password></inn:getCategoriesbyVendorID>

    </soap:Body></soap:Envelope>",userName,password);

        //StringEntity input = new StringEntity("<soap:Envelope 

    xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:inn=\"http:Innovation/\">

    <soap:Header/><soap:Body><inn:getCategoriesbyVendorID><!--Optional:-->

    <userName>Nicole</userName><!--Optional:--><password>Nicole</password>

    </inn:getCategoriesbyVendorID></soap:Body></soap:Envelope>");  

        post.setEntity(input);

        HttpResponse response = client.execute(post);

        BufferedReader rd = new BufferedReader(new 

    InputStreamReader(response.getEntity().getContent()));

        String line = "";

        while ((line = rd.readLine()) != null) {

        System.out.println(line);

使用上面的代码,实体会抛出错误。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您的字符串格式的语法没有任何问题。

  

它在eclipse中显示错误,即更改HTTP的输入类型   entity(post.set Entity(input);)。

错误是因为HttpPost.setEntity在为其指定String类型时需要类型为HttpEntity的参数。

尝试设置org.apache.http.entity.StringEntity代替:

HttpEntity entity = new StringEntity(input); //Your formatted String 
post.setEntity(entity);