Java HttpURLConnection post方法将参数传递给cgi

时间:2013-12-11 04:16:20

标签: java post cgi httpurlconnection

我是Java网络编程的新手。我正在使用HttpURLConnection通过POST将数据发送到服务器。我设置标题然后获取输出流并写入一些字节然后关闭输出流。据我所知,这是正确的方法,但服务器发给我一个未知的例外。

你能否给我一些暗示为什么会发生这种异常

 public static void main(String[] args) throws Exception {
        String url = "http://www.nlm.nih.gov/cgi/mesh/2014/MB_cgi";
        String cookie = retrieveCookies(url);
        String urlParameters = "?term=Cancer&exact=Find Exact Term&field=all";
        String page = postHttpPage(url , urlParameters, cookie);
        System.out.println(page);
        System.out.println();
    }

    public static String postHttpPage(String url, String urlParameters, String cookie) throws Exception {
        System.out.println("\nSending 'POST' request to URL : " + url);
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        return postPage(conn, urlParameters, cookie);
    }

    private static String postPage(HttpURLConnection conn, String urlParameters, String cookie) throws Exception {
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
        conn.setRequestProperty("Content-Language", "en-US");
        conn.setRequestProperty("Cookie", cookie);
        //conn.setInstanceFollowRedirects(true);
        // Send post request
        //conn.setDoInput(true);
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);
        //System.out.println("wr : " + wr.size());
        wr.flush();
        wr.close();

        StringBuilder response = new StringBuilder();
        int responseCode = conn.getResponseCode();
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static String retrieveCookies(String url) throws IOException{  
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        String cookies=conn.getHeaderField("Set-Cookie");  
        System.out.print("cookies: " + cookies);
        conn.disconnect();
        return cookies; 
    }  

1 个答案:

答案 0 :(得分:0)

问题在于服务器。如果您发送了许多请求,服务器没有回复您,有时它也不起作用可能是由于请求量很大。