使用Java发送Http请求的内容

时间:2022-08-07 23:40:29

公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容。这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过。

学习了Java两种方式,一种是用java.net.URLConnection,另一种则是大名鼎鼎的HttpClient。效率上没有做深入研究,使用java.net.URLConnection比较麻烦,而HttpClient就比较惬意。

java.net.URLConnection方法:

private static void urlConnectionPost() {
    StringBuilder responseBuilder = null;
    BufferedReader reader = null;
    OutputStreamWriter wr = null;

URL url;
    try {
        url = new URL(TEST_URL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(1000 * 5);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write("");
        wr.flush();

// Get the response
        reader = new BufferedReader(new InputStreamReader(conn
                .getInputStream()));
        responseBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            responseBuilder.append(line + "\n");
        }
        wr.close();
        reader.close();

System.out.println(responseBuilder.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

HttpClient方法:

private static void httpClientPost() {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(TEST_URL);

try {
        ContentProducer cp = new ContentProducer() {
            public void writeTo(OutputStream outstream) throws IOException {
                Writer writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("");
                writer.flush();
            }
        };

post.setEntity(new EntityTemplate(cp));
        HttpResponse response = client.execute(post);
   
        System.out.println(EntityUtils.toString(response.getEntity()));
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}