java - HTTP request

 The following shelf packages are required:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.9</version>
		</dependency>

 get request and post request tools

/**
     * get请求工具类
     * @param url
     * @return
     */
    public static JSONObject doGetStr(String url){
        //创建HTTP请求客户端
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        //创建HTTP  get请求
        HttpGet httpGet = new HttpGet(url);
        //创建返回结果
        JSONObject jsonObject = null;
        //获取响应结果
        try {
            HttpResponse response = httpclient.execute(httpGet);
            //获取消息体中的结果
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String strEntity = EntityUtils.toString(entity,"UTF-8");
                jsonObject = JSONObject.fromObject(strEntity);
            }
        } catch (Exception e) {
            System.out.println(new Date()+"GET请求失败");
            return null;
        }
        return jsonObject;
    }
/**
     * POST请求工具类
     */
    public static JSONObject doPostStr(String url,String strOut){
        //创建HTTP请求客户端
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        //创建Post请求
        HttpPost httpPost = new HttpPost(url);
        //创建返回结果
        JSONObject jsonObject = null;
        //设置请求参数
        try {
            httpPost.setEntity(new StringEntity(strOut,"UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            //获取消息体中的结果
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String strEntity = EntityUtils.toString(entity,"UTF-8");
                jsonObject = JSONObject.fromObject(strEntity);
            }
        } catch (Exception e) {
            System.out.println(new Date()+"POST请求失败");
            return null;
        }
        return jsonObject;
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325808115&siteId=291194637