ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

HttpClient--使用HttpClient进行Get Post请求访问

2021-10-25 23:35:34  阅读:174  来源: 互联网

标签:http String Get -- new org apache import HttpClient


在java后台开发中,我们有时候需要调用其他网站的接口进行数据的获取操作,我们一般会采用

  1.java net 包中的URL 类,进行网络的数据获取

  2.使用apache提供的HttpClient进行网络中数据的获取;

 

这里我们使用第二种方式,使用apache 提供的HttpClient进行数据的获取,接口的对接,下面附上HttpClientUtil 工具类,实现了POST与GET方法

1.引入pom依赖

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>

package com.project.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientUtils {
    
    
    
    
    
    //使用HttpClient 进行doGET请求
    public static String doGet(String url) throws Exception {
        
        CloseableHttpClient httpclient =HttpClients.createDefault();
        HttpGet httpget =new HttpGet(url);
        try {
            HttpResponse response=httpclient.execute(httpget);
            //创建响应处理器处理服务器响应内容
            String content =  Utf8ResponseHandler.INSTANCE.handleResponse(response);
            
            return content;
           
            }
           
        finally {
            httpget.releaseConnection();
          }
        
    }
    
    
    
    
    
    public static void main(String[] args) throws Exception {
        
        
        String str=doPOST("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN","nm");
        System.out.println(str);
        
        
    }
    
    
    
    
    
    //使用HttpClient 进行dopOSTT请求,适合发送的数据为json数据格式
        public static String doPOST(String url,String outstr) throws Exception {
            
            
            //DefaultHttpClient httpclient =new DefaultHttpClient();//老版本的方法
            CloseableHttpClient httpclient =HttpClients.createDefault();
            HttpPost httppost =new HttpPost(url);
            String result =null;
            try {
                httppost.setEntity(new StringEntity(outstr, "UTF-8"));
                HttpResponse response=httpclient.execute(httppost);
                //创建响应处理器处理服务器响应内容
                String content =  Utf8ResponseHandler.INSTANCE.handleResponse(response);
          
                return content;
        
            }
            finally {
                
                httppost.releaseConnection();
            }
    
    
        }



    
//传递form 表单
public static String NameValue(String URL,Map<String,String> formArgs) throws Exception {

HttpClient httpclient = HttpClients.createDefault();

HttpPost post =new HttpPost(URL);

List<BasicNameValuePair> data =new ArrayList<BasicNameValuePair>();

for(Map.Entry<String, String> entry :formArgs.entrySet()) {

data.add(new BasicNameValuePair(entry.getKey(), entry.getValue()) );
}
try {
post.setEntity(new UrlEncodedFormEntity(data));

HttpResponse response=httpclient.execute(post);

String content = Utf8ResponseHandler.INSTANCE.handleResponse(response);

return content;
}
finally {

post.releaseConnection();
}


}



}
创建响应处理器--utf-8编码(需要继承ResponseHandler 实现自己的方法,官方也有自己默认的一套实现方法BasicResponseHandler,但不能设置编码)

package com.project.utils;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;


public class Utf8ResponseHandler implements ResponseHandler<String> {

    /*
     *实现utf-8编码的返回数据类型,实现ttpclient ResponseHandler接口方法
     *
     *copy from {@link org.apache.http.impl.client.BasicResponseHandler}官方默认提供
     */
    public static final ResponseHandler<String> INSTANCE = new Utf8ResponseHandler();
    
    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
         final StatusLine statusLine = response.getStatusLine();
            final HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
              EntityUtils.consume(entity);
              throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
          }


    }

 

标签:http,String,Get,--,new,org,apache,import,HttpClient
来源: https://www.cnblogs.com/wangfx/p/15463776.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有