httpclient4例子

摘要:
参考:http://hc.apache.org/httpclient-3.x/tutorial.htmlimportorg.apache.http.HttpEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.

参考:http://hc.apache.org/httpclient-3.x/tutorial.html

importorg.apache.http.HttpEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.protocol.HTTP;
importorg.apache.poi.util.IOUtils;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Component;

importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.net.HttpURLConnection;
importjava.net.URL;

@Component
public classHttpClientUtil {
    private static CloseableHttpClient httpClient =HttpClients.createDefault();

    private staticString ADDRESS;

    public staticString getAuthorization() {
        String url = "http://" + ADDRESS + "/login";
        String data = "{"username": "username","password": "password"}";
        HttpURLConnection connection=null;
        try{
            URL server = newURL(url);
            connection =(HttpURLConnection)server.openConnection();
            connection.setRequestMethod("POST");
            connection.addRequestProperty("Content-Type","application/json;charset=utf-8");
            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(5*1000);
            connection.setReadTimeout(10*1000);
            DataOutputStream wr = newDataOutputStream(connection.getOutputStream());
            wr.write(data.toString().getBytes("UTF-8"));
            wr.flush ();
            wr.close ();

            String Authorization =connection.getHeaderField("Authorization");
            returnAuthorization;
        } catch(Exception e){
            e.printStackTrace();
        } finally{
            if(connection != null){
                connection.disconnect();
            }
        }
        return null;
    }

    public staticString post(String url, String body) {
        String auth =getAuthorization();
        if (auth == null) {
            return null;
        }

        HttpPost httpPost = new HttpPost("http://" + ADDRESS +url);
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
        httpPost.setHeader("Accept", "application/json;charset=UTF-8");
        httpPost.setHeader("Authorization", auth);

        CloseableHttpResponse response2 = null;
        try{
            StringEntity entity = new StringEntity(body, "utf-8");
            System.out.println("request = " +body);

            httpPost.setEntity(entity);

            response2 =httpClient.execute(httpPost);
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 =response2.getEntity();
            String responseStr = newString(IOUtils.toByteArray(entity2.getContent()));
            System.out.println("response = " +responseStr);

            returnresponseStr;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        } finally{
            if (response2 != null) {
                try{
                    response2.close();
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Value("${interface.address}")
    public voidsetAddress(String address) {
        ADDRESS =address;
    }
}

免责声明:文章转载自《httpclient4例子》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android应用签名这几个好用的 Google 搜索技巧,让你飞起!下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WordPress插件制作教程(三): 添加菜单的方法

上一篇编写了一个简单的插件,让大家对插件的简单制作有个了解,这一篇我们在更深一步,当我们激活插件后后台会显示菜单出来,然后通过单击菜单显示自己定义好的信息。激活之后会在WordPress后台显示一个菜单,下面会有多个子菜单,如下图: 1. 在WordPress后台添加一个同级主菜单,在主菜单下添加子菜单 // add_menu_page( $page_t...

string.format()

Lua提供了string.format()函数来生成具有特定格式的字符串, 函数的第一个参数是格式(formatstring), 之后是对应格式中每个代号的各种数据. 由于格式字符串的存在, 使得产生的长字符串可读性大大提高了. 这个函数的格式很像C语言中的printf().函数string.format在用来对字符串进行格式化的时候,特别是字符串输出,是...

C#从数据库mysql读取数据

usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; u...

Delphi声明Record变量后直接初始化

 TARec = record    A1: string;    A2: string;  end;   TBRec = record    A1: string;    A2: string;    ARec: TARec;  end;   PAppWindow = ^TAppWindow;  TAppWindow = Record    Width,...

js Base64与字符串互转

1、base64加密 在页面中引入base64.js文件,调用方法为: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>base64加密</title> <script type="text/jav...

记录Java8中的字符串转数组再通过指定符号拼接

1.字符串转换字符串数组 String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); // nameAttr="made,in;china,;qqq,.aaa" ,MULTI_VALUE_ATTRIBUTE_DELIMI...