• org.apache.httpcomponents httpclient 发起HTTP JSON请求


    1. pom.xml

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
    

    2. HttpClient.java

    package com.midea.clean.util;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    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.client.methods.HttpUriRequest;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.alibaba.fastjson.JSONObject;
    import com.midea.clean.bo.UserBo;
    
    public class HttpClient {
    	
    	private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class); 
    
    	/**
    	 * 发送post请求
    	 * @param url
    	 * @param params
    	 * @return
    	 */
    	public static String post(String url, Map<String, String> params) {
    		DefaultHttpClient httpclient = new DefaultHttpClient();
    		String body = null;
    
    		HttpPost post = postForm(url, params);
    
    		body = invoke(httpclient, post);
    
    		httpclient.getConnectionManager().shutdown();
    
    		return body;
    	}
    
    	/**
    	 * 发送get请求
    	 * @param url
    	 * @return
    	 */
    	public static String get(String url) {
    		DefaultHttpClient httpclient = new DefaultHttpClient();
    		String body = null;
    
    		HttpGet get = new HttpGet(url);
    		body = invoke(httpclient, get);
    
    		httpclient.getConnectionManager().shutdown();
    
    		return body;
    	}
    
    	private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) {
    
    		HttpResponse response = sendRequest(httpclient, httpost);
    		String body = paseResponse(response);
    
    		return body;
    	}
    
    	private static String paseResponse(HttpResponse response) {
    		HttpEntity entity = response.getEntity();
    
    		String charset = EntityUtils.getContentCharSet(entity);
    
    		String body = null;
    		try {
    			body = EntityUtils.toString(entity);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		return body;
    	}
    
    	private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {
    		HttpResponse response = null;
    
    		try {
    			response = httpclient.execute(httpost);
    		} catch (ClientProtocolException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return response;
    	}
    
    	private static HttpPost postForm(String url, Map<String, String> params) {
    
    		HttpPost httpost = new HttpPost(url);
    		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    		// 需要传一个token
    		//httpost.setHeader("token", "c7a4e021-6527-11e6-96be-fcaa14c3021a1");
    		Set<String> keySet = params.keySet();
    		for (String key : keySet) {
    			nvps.add(new BasicNameValuePair(key, params.get(key)));
    		}
    
    		try {
    			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		}
    
    		return httpost;
    	}
    	
    	 /** 
         * post方式提交json代码 
         * @throws Exception  
         */  
        public static String postJson(String url,String json) throws Exception{  
            //创建默认的httpClient实例.   
            CloseableHttpClient httpclient = null;  
            //接收响应结果  
            CloseableHttpResponse response = null;  
            String result = "";
            //创建httppost  
            httpclient = HttpClients.createDefault();    
            HttpPost httpPost = new HttpPost(url);  
            httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");  
            //参数  
            StringEntity se = new StringEntity(json);  
            se.setContentEncoding("UTF-8");  
            se.setContentType("application/json");//发送json需要设置contentType  
            httpPost.setEntity(se); 
            LOGGER.debug("http post url:{},json:{}",url,json);
            response = httpclient.execute(httpPost);  
            LOGGER.debug("http post result:{}", response);
            //解析返结果  
            HttpEntity entity = response.getEntity();   
            if(entity != null){  
            	result = EntityUtils.toString(entity, "UTF-8");   
            }  
            httpclient.close();  
            response.close();  
            return result;
        }  
    
    	public static void main(String[] args) throws Exception {
    //		HttpClient.get("http://localhost/clean/4a/welcome");
    		
    //		Map<String,String> params = new HashMap<String,String>();
    //		params.put("empName", "1");
    //		params.put("empCode", "2");
    //		HttpClient.post("http://localhost/clean/4a/privilege/check", params);
    		
    		UserBo userBo = new UserBo();
        	userBo.setEmpCode("3");
        	userBo.setEmpName("zs");
        	userBo.setErpUid("4");
        	userBo.setMip("5");
        	String jsonStr = JSONObject.toJSONString(userBo);
        	
    		HttpClient.postJson("http://localhost/clean/4a/privilege/check", jsonStr);
    	}
    	
    }
    

      

  • 相关阅读:
    Xamarin.Android和UWP之MVVM的简单使用(二)
    Xamarin.Android和UWP之MVVM的简单使用(一)
    那些年用过的xUnit.net的简单用法
    Xamarin.Android之给我们的应用加点过渡效果
    Xamarin.Android之Splash的几种简单实现
    Xamarin.Android之布局文件智能提示问题
    Xamarin.Android之Spinner的简单探讨
    Xamarin.Android之封装个简单的网络请求类
    Xamarin.Android再体验之简单的登录Demo
    【分库分表】sharding-jdbc实践—分库分表入门
  • 原文地址:https://www.cnblogs.com/yun965861480/p/6906207.html
Copyright © 2020-2023  润新知