java HttpClient客户端访问 http

package com.gofun.person.web.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 
 * @Title: httpClient 工具
 * @Package
 * @Description:
 * @date 2018/6/617:15
 */
public class HttpUtil {

    private HttpClient client;

    {
       client = HttpClients.createDefault();
    }
    //get请求
    public HashMap  getHttpRequest(String urlPath){
        HashMap result;
        HttpGet requests = new HttpGet(urlPath);
        requests.setHeader("Accept","application/json");
        try {
            HttpResponse response = client.execute(requests);
            HttpEntity entity = response.getEntity();
            ObjectMapper mapper = new ObjectMapper();
            result = mapper.readValue(entity.getContent(), HashMap.class);
        } catch (IOException e) {
            throw new RuntimeException("HTTP GET Request Failed with Error code : "
                    + e.getMessage());
        }
        return result;
    }

    //post请求
    public HashMap  postHttpRequest(String urlPath, List param){
        HashMap result;
        HttpPost requests = new HttpPost(urlPath);
        requests.setHeader("Content-Type","application/json");
        try {
            requests.setEntity(new UrlEncodedFormEntity(param, "utf-8"));
            HttpResponse response = client.execute(requests);
            HttpEntity entity = response.getEntity();
            ObjectMapper mapper = new ObjectMapper();
            result = mapper.readValue(entity.getContent(), HashMap.class);
        } catch (IOException e) {
            throw new RuntimeException("HTTP post Request Failed with Error code : "
                    + e.getMessage());
        }
        return result;
    }

}

你可能感兴趣的:(java HttpClient客户端访问 http)