1

我有一个 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();

没有错误,但没有成功发送数据。告诉我为什么?以及任何解决方案?

4

2 回答 2

1

您可以使用更友好的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.
于 2012-11-12T10:47:08.013 回答
0

使用查询参数创建 URL。

URL url= new URL("http://localhost:8118/log.srv?action=likearticle&noname=989858&ladoi=cutymaraton"+i);
于 2012-11-12T10:42:26.903 回答