Java - 在同一连接上执行http请求POST和GET

时间:2012-07-06 15:13:31

标签: java httpurlconnection http-request

我有一些我想要实现的目标。

我在端口8080上的本地主机上运行了一个Web应用程序。

我在localhost上运行了一个HTTP Server:9005。

我有一个JSP表单,它将信息传递给servlet java类,后者依次使用数据字符串对HTTP Server localhost:9010上的URL执行HTTP发布。

我需要做的是执行POST和GET作为同一连接的一部分。我让它们作为两个单独的呼叫工作,但不是在同一个连接上。它需要是相同的连接,因为我发布数据,HTTP Server获取此数据,处理它并将唯一数据输出到此URL。因此,GET需要与POST一样成为同一连接的一部分。

有人可以帮忙吗?

这是我的Process Request java代码:

    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import javax.servlet.*;
    import javax.servlet.http.*;


    import java.util.List; 
    import java.util.Map.Entry; 

    public class ProcessRequest {

        public void sendRequestToGateway() throws Throwable{

            String message = URLEncoder.encode("OP1387927", "UTF-8");    

            try {           
                URL url = new URL("http://localhost:9005/json");            
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();            
                connection.setDoOutput(true);            
                connection.setRequestMethod("POST");            
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());           
                writer.write("operator=" + message);       
                writer.close();   

                System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
                System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 

                    receiveMessageFromGateway();

                } else {                
                    // Server returned HTTP error code.            
                }   

                //receiveMessageFromGateway();

            } catch (MalformedURLException e) {            
                // ...        
            } catch (IOException e) {           
                    // ...        
            }
        }

        public void receiveMessageFromGateway()  throws Throwable { 


            HttpURLConnection client = null; 
            OutputStreamWriter wr = null; 
            BufferedReader rd = null; 
            StringBuilder sb = null; 
            String line = null; 

            try { 

              URL url = new URL("http://localhost:9005/json"); 
              client = (HttpURLConnection) url.openConnection(); 
              client.setRequestMethod("GET"); 
              client.setDoOutput(true); 
              client.setReadTimeout(10000); 

              client.connect(); 
              System.out.println(" *** headers ***"); 
              for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) { 
                System.out.println(headernew.getKey() + "=" + headernew.getValue()); 
              } 

              System.out.println(" \n\n*** Body ***"); 
              rd = new BufferedReader(new InputStreamReader(client.getInputStream())); 
              sb = new StringBuilder(); 

              while ((line = rd.readLine()) != null) { 
                sb.append(line + '\n'); 
              } 

              System.out.println("body=" + sb.toString()); 

            } finally { 
              client.disconnect(); 
              rd = null; 
              sb = null; 
              wr = null; 
            } 
         }  

    }

3 个答案:

答案 0 :(得分:3)

为什么不直接从原始POST返回结果?

答案 1 :(得分:1)

通常,您无法使用HttpUrlConnection控制连接重用。您可能能够将连接转换为特定的实现类并干扰它,但这是一种非常不稳定的方式。

根据要求,Apache HttpClient可能是更好的选择。

答案 2 :(得分:0)

您可以使用Apache HTTP Client进行此操作。它非常简单。

如果您使用的是maven,只需将以下行添加到POM文件中:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.3</version>
</dependency>   

在这个例子中,我正在提交一个POST请求,然后是一个GET请求。

看看:

public static String get(String p_url) throws IOException
{       

        CloseableHttpClient httpclient = HttpClients.createDefault();

        // First request: POST
        HttpPost httpPost = new HttpPost("http://the-api-url.com/Login/Auth&token=12345"));
        CloseableHttpResponse response_post = httpclient.execute(httpPost);                 
        System.out.println(response_post.getStatusLine());          
        HttpEntity entity_post = response_post.getEntity();         
        System.out.println(EntityUtils.toString(entity_post));

        // Second request: GET
        HttpGet httpGet = new HttpGet(p_url);
        CloseableHttpResponse response_get = httpclient.execute(httpGet);  
        System.out.println(response_get.getStatusLine());           
        HttpEntity entity_get = response_get.getEntity();           
        System.out.println(EntityUtils.toString(entity_get));

        response_post.close();
        response_get.close();           
        return EntityUtils.toString(entity_get);             
    }