通过java将查询字符串直接发送到httpHandler

时间:2012-11-12 10:29:33

标签: java http-post httphandler

我有一个http处理程序,位于:

http://localhost:8118/log.srv

当我在IE上粘贴此网址时,它运行良好。

http://localhost:8118/log.srv?action=likearticle&noname=989858&ladoi=cutymaraton

http处理程序获取数据。

但是当我使用java程序发布数据时,不会发生错误,但是,http处理程序无法获取任何数据。 我的java程序:

public static void main(String[] args) {
        try {
            for(int i=1; i<1000; i++){
                URL url= new URL("http://localhost:8118/log.srv");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                String data = "action=likearticle&noname=989858&ladoi=cutymaraton"+i;
                System.out.println(data);
                writer.write(data);
                writer.flush();
            }

            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

我使用其他代码:

String urlParameters = "action=likearticle&noname=989858&ladoi=cutymaraton";
            String request = "http://localhost:8118/log.srv";
            URL url = new URL(request); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST"); 
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setUseCaches (false);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            connection.disconnect();

没有错误,但没有成功发送数据。 告诉我为什么?对此有什么解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以使用more friendly API,如下所示:

PostMethod post = new PostMethod("http://localhost:8118/log.srv");
post.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
NameValuePair[] data = {
  new NameValuePair("action", "likearticle"),
  new NameValuePair("noname", "989858"),
  new NameValuePair("ladoi", "cutymaraton")
};
post.setRequestBody(data);    

HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);

InputStream in = post.getResponseBodyAsStream();
// handle response.

答案 1 :(得分:0)

使用查询参数创建URL。

URL url= new URL("http://localhost:8118/log.srv?action=likearticle&noname=989858&ladoi=cutymaraton"+i);