0

我尝试发送发布请求,但网络服务器返回我没有添加任何发布值。我花了很多时间试图解决这个问题,但没有结果。这是代码:

    public static String post(String url, String postParams)
{
    URLConnection connection = null;
    try
    {
        connection = initializeConnection(url);
        connection.setDoOutput(true);
        ((HttpURLConnection) connection).setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestProperty("Accept", "text/xml");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postParams.getBytes());

        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        return inputStreamToString(is);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;

    }
}

protected static HttpURLConnection initializeConnection(String stringUrl)
{
    HttpURLConnection connection;
    URL url = null;
    try
    {
        url = new URL(stringUrl);
    }
    catch (MalformedURLException e1)
    {
        e1.printStackTrace();
    }
    try
    {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }

    return connection;
}

public static String inputStreamToString(InputStream is)
{
    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    StringBuilder total = new StringBuilder();
    String line;
    try
    {
        while ((line = r.readLine()) != null)
        {
            total.append(line);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return total.toString();
}

我从网络服务器收到一条消息,告诉我没有添加任何后值。据我从代码中了解,添加了值。我被困住了。

4

2 回答 2

1

原来我所要做的就是更换

connection.setRequestProperty("Content-Type", "text/xml");

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

如此简单,花费了如此多的时间来清除它......顺便说一句,我怎么知道服务器需要这个标头?我认为对请求至关重要的所有工作都将由 java 自动完成。

PS 安装提琴手帮助解决了这个问题,谢谢。

于 2012-12-28T15:04:39.353 回答
0

调试“postParams”参数并检查发送的内容。

于 2012-12-28T13:47:51.667 回答