发送http请求到linux服务器

时间:2011-02-16 04:25:56

标签: java c web-services http

我必须向我们在Linux机器上运行的C程序发送HTTP请求。如何将Java中的HTTP请求发送到C中并在Linux机器上运行的服务器?

4 个答案:

答案 0 :(得分:1)

 public void sendPostRequest() {

    //Build parameter string
    String data = "width=50&height=100";
    try {

        // Send the request
        URL url = new URL("http://www.somesite.com");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        //write parameters
        writer.write(data);
        writer.flush();

        // Get the response
        StringBuffer answer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            answer.append(line);
        }
        writer.close();
        reader.close();

        //Output the response
        System.out.println(answer.toString());

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

以上示例用于使用URL发送POST请求。

答案 1 :(得分:0)

如果您询问如何将Java中的HTTP请求发送到用C编写的Web服务器,则可以使用URLConnection类。

答案 2 :(得分:0)

try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
    // Process line...
}
wr.close();
rd.close(); } catch (Exception e) { }

以上示例用于使用URL发送POST请求。 另请参阅Sun Tutorial阅读/写入URLConnection。另一种选择是使用Apache HTTPComponents,其中包含HttpCoreHttpClient模块的示例。 如果您正在考虑实现Web服务器,您将必须自己处理Http请求,其中涉及线程池,解析请求,生成HTML,安全性,多个会话等,或者使用现成的方式遵循简单的路由像Apache这样的Web服务器,可以看到Perl,Ruby等所有高级语言都可用于开发Web应用程序。 要实现您自己的Http服务器,请查看Micro-HttpdtinyHttpd 您可能还想查看包含示例代码的Adding Web Interface -C++ application

答案 3 :(得分:0)

从问题的措辞方式来看......我认为在开始之前你需要了解一些基本的东西。尝试使用Google搜索来获取有关Web服务器工作方式的简单指南。

一旦掌握了基本想法,C程序员就有几个选择:

1)您希望C程序持续运行,等待来自Java的请求。

在这种情况下,您必须编写C程序代码以打开Socket和Listen for connections。例如,请参阅http://www.linuxhowtos.org/C_C++/socket.htm

OR

2)您的服务器上有一个Web服务器,每次发出特定请求时都会运行您的C程序?在这种情况下,您必须将C编码为CGI程序。例如,请参阅http://www.cs.tut.fi/~jkorpela/forms/cgic.html

提示:(2)更容易!