常用的httpclient请求接口demo

初始化端口

private static ThreadSafeClientConnManager cm = null;
    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
                .getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        cm = new ThreadSafeClientConnManager(schemeRegistry);
        cm.setMaxTotal(MAX_TOTAL);  
        cm.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION);
    }

初始化请求的客户端

    public static HttpClient getHttpClient() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
               HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); // 3000ms
//        return new DefaultHttpClient(cm, params);
        //代理
       DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
        httpProxy(httpClient);
         return httpClient;
    }

添加代理

    public static void httpProxy(DefaultHttpClient httpClient){
        String proxyHost = "10.36.232.126";
        int proxyPort = 8080;
        String userName = "";
        String password = "";
        httpClient.getCredentialsProvider().setCredentials(
          new AuthScope(proxyHost, proxyPort),
          new UsernamePasswordCredentials(userName, password));
        HttpHost proxy = new HttpHost(proxyHost,proxyPort);
        httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
    }

发送带图片的接口

    public String postMultipart(String url, Map params,File file) {

        String body = null;
        try {
            // Post请求
            HttpPost httppost = new HttpPost(url);
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            entityBuilder.setCharset(Consts.UTF_8);

            for (Map.Entry entry : params.entrySet()){
                entityBuilder.addTextBody(entry.getKey(), entry.getValue());
            }


            entityBuilder.addPart("file", new FileBody(file));
            httppost.setEntity(entityBuilder.build());


            HttpResponse httpresponse = getHttpClient().execute(httppost);
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
              System.out.println("entity != null");
                entity.consumeContent();
            }

        } catch (Exception e) {
            log.error("error when send post", e);
        }
        return body;
    }

Get请求,参数为List

    public String get(String url, List params) {

        String body = null;
        try {
            // Get请求
            HttpGet httpget = new HttpGet(url);
            // 设置参数
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
            // 发送请求
            HttpResponse httpresponse = getHttpClient().execute(httpget);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (Exception e) {
            log.error("error when send get", e);
        }
        return body;
    }

Post请求,参数为List

    /**
     * 
     * // Post请求
     * 
     * @param url
     * 
     * @param params
     * 
     * @return
     */

    public String post(String url, List params) {

        String body = null;

        try {
            // Post请求
            HttpPost httppost = new HttpPost(url);
            // 设置参数
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            // 发送请求
            HttpResponse httpresponse = getHttpClient().execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }

        } catch (Exception e) {
            log.error("error when send post", e);
        }
        return body;
    }

Post接口 参数为Map

    /**
     * 创建post请求方法
     * 
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public String post(String url, Map params) throws Exception {

        log.debug("init create post request method……");

        try {

            List nvps = new ArrayList();

            Set> set = params.entrySet();
            Iterator> iter = set.iterator();
            while (iter.hasNext()) {
                Entry entry = iter.next();
                String key = entry.getKey();
                String value = entry.getValue();
                nvps.add(new BasicNameValuePair(key, value));
            }

            HttpPost post = new HttpPost(url);
            post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse response = getHttpClient().execute(post);

            log.debug("exit create post request method……");
            return EntityUtils.toString(response.getEntity());
        } catch (UnsupportedEncodingException e) {

            log.error("添加post参数异常……", e);
            throw new Exception("添加post参数异常……", e);
        } catch (Exception e) {

            log.error("创建Post请求异常……", e);
            throw new Exception("创建Post请求异常……", e);
        }
    }```

你可能感兴趣的:(常用的httpclient请求接口demo)