jsp使用httpclient发送post请求_jsp使用HttpClient发送Post请求例子

时间:2018-12-16  来源:WebService  阅读:

司要将自己的产品封装一个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();
    }
}

jsp使用httpclient发送post请求_jsp使用HttpClient发送Post请求例子

http://m.bbyears.com/asp/46569.html

推荐访问:
相关阅读 猜你喜欢
本类排行 本类最新