关注微信公众号 太平洋学习网 扫描二维码
最新消息:关注【太平洋学习网】微信公众号,可以获取全套资料,【全套Java基础27天】【JavaEE就业视频4个月】【Android就业视频4个月】

httpClientUtils工具类发送GET或POST请求完整案例

Javaweb 太平洋学习网 浏览 评论

httpClient是javaEE语言中用于接口调用的框架,本案例封装好了httpClientUtils工具类,用于发送GET和POST请求,直接将此工具类复制到你的项目中就可以了。

第一步:httpClient jar包可采用maven方式下载,version版本自己改,如下;

<dependency>
	<groupId>javax.servlet.jsp</groupId>
	<artifactId>jsp-api</artifactId>
	<version>2.2</version>
</dependency>

<dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>3.1</version>
</dependency>

第二步:新建httpClientUtils.java工具类,将此内容复制到你的项目中。

package cn.com.baidu.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {

	public static String getContentFromUrl(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			HttpGet request = new HttpGet(url);

			request.setHeader(HttpHeaders.USER_AGENT,
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
			request.setHeader(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, sdch");
			request.setHeader(HttpHeaders.CONNECTION, "keep-alive");
			CloseableHttpResponse httpResponse = null;
			httpResponse = httpClient.execute(request);
			try {
				HttpEntity entity = httpResponse.getEntity();
				if (null != entity) {
					return EntityUtils.toString(entity);
				}
			} finally {
				httpResponse.close();
			}

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

	public static InputStream getStreamFromUrl(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet request = new HttpGet(url);

		request.setHeader(HttpHeaders.USER_AGENT,
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
		request.setHeader(HttpHeaders.ACCEPT,
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, sdch");
		request.setHeader(HttpHeaders.CONNECTION, "keep-alive");
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(request);
			HttpEntity entity = httpResponse.getEntity();
			if (null != entity) {
				return entity.getContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
    public static String doPost(String url,Map<String,String> map,String charset){  
    	CloseableHttpClient httpClient = HttpClients.createDefault(); 
        HttpPost httpPost = new HttpPost(url);;  
        String result = null;  
        try{     
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();   
            //遍历map集合
            for(Map.Entry<String, String> entry :map.entrySet()){
            	list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            if(list.size() > 0){  
            	//charset=utf-8或者gbk2312
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,charset);  
                }  
            }  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}  
        return result;  
    }  
}

第三步:使用httpClientUtils工具类发送get,post请求案例。

public class TestMain {
	//发送get请求,拼接参数
	public void testPost(){  
		String url = "https://192.168.1.101/login?username=xxx&password=xxxx";
		String result = httpClientUtils.getContentFromUrl(url);  
		System.out.println("get登录结果:"+result);  
	}   
    //发送post请求,form表单参数
    public void testPost(){  
      String url = "http://192.168.1.101/login";
      String charset = "utf-8";
      Map<String,String> loginMap = new HashMap<String,String>();  
      loginMap.put("username","*****");  
      loginMap.put("password","*****");  
      String result = httpClientUtils.doPost(url,loginMap,charset);  
      System.out.println("post登录结果:"+result);  
    }  
      
    public static void main(String[] args){  
       testPost();
       testPost();  
    }  
}


来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/javaweb/2017/0612/115.html

    与本文相关的文章