• 使用Java发送Http请求的内容


    公司要将自己的产品封装一个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 + " ");
            }
            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();
        }
    }
  • 相关阅读:
    【Codeforces 776B】Sherlock and his girlfriend
    BZOJ4942 NOI2017整数(线段树)
    BZOJ4516 SDOI2016生成魔咒(后缀数组+平衡树)
    BZOJ4943 NOI2017蚯蚓排队(哈希+链表)
    Codeforces Round#500 Div.2 翻车记
    BZOJ5093 图的价值(NTT+斯特林数)
    BZOJ2821 作诗(分块)
    BZOJ2724 [Violet]蒲公英(分块)
    BZOJ2001 HNOI2010城市建设(线段树分治+LCT)
    BZOJ1093 ZJOI2007最大半连通子图(缩点+dp)
  • 原文地址:https://www.cnblogs.com/peijie-tech/p/3543387.html
Copyright © 2020-2023  润新知