post 请求方式 两种方式, get请求一种方式

package com.kingdee.eas.wbshr.beisen.util;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
 import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
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.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import com.kingdee.eas.tm.im.httpClient.SSLClient;


public class BeiSenConnUtil {

	private static String APP_ID = "******";
	
	private static String TENANT_ID = "********";
	
	private static String GRANT_TYPE = "client_credentials";
	
	private static String SRCRET = "*****************";
	
	private static String TOKEN_URL = "*********************";
	
	public static String getAcessToken() throws IOException {

		String urlStr = TOKEN_URL;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("app_id", APP_ID);
		map.put("tenant_id", TENANT_ID);
		map.put("grant_type", GRANT_TYPE);
		map.put("secret", SRCRET);
		JSONObject paramJson = JSONObject.fromObject(map);

		StringBuffer sBuffer = new StringBuffer("");
		try {
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.write(paramJson.toString().getBytes());
			outputStream.flush();
			outputStream.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			while ((line = reader.readLine()) != null) {
				line = new String(line.getBytes(), "UTF-8");
				sBuffer.append(line);
			}
			System.out.println(sBuffer);
			reader.close();
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sBuffer.toString();
	}

	 /**
	  * 该方法bos 发送post请求,第三方返回接口信息乱码
	  */
	public static String getDataFromBeisen(String urlStr, JSONObject paramEmpJson, String accessToken) throws IOException {
		
		StringBuffer sBuffer = new StringBuffer("");
		try {
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//utf-8
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("Authorization","Bearer "+ accessToken);
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.write(paramEmpJson.toString().getBytes());
			outputStream.flush();
			outputStream.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = "";
			while ((line = reader.readLine()) != null) {
				line = new String(line.getBytes(), "UTF-8");
				sBuffer.append(line);
			}
			//System.out.println(sBuffer);
			reader.close();
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sBuffer.toString();
	}
	
	
	/**
	 * 该方法bos 发送post请求,第三方返回接口信息不乱码

	 * @param url
	 * @param paramEmpJson
	 * @param accessToken
	 * @return
	 * @throws IOException
	 */
	public static String getDataFromBeisenmz(String url, JSONObject paramEmpJson, String accessToken) throws IOException {
		String result = null;
		StringBuffer sBuffer = new StringBuffer("");
		try {
	        HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-Typ", "application/json;charset=UTF-8");
			httpPost.setHeader("Accept", "application/json");
			httpPost.addHeader("Authorization", "Bearer "+ accessToken);
			httpPost.addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			StringEntity   entity=	new StringEntity(paramEmpJson.toString(),"UTF-8");
			String  charset = "UTF-8";
			entity.setContentType("application/json; charset=" + charset);
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}  
 
	
}







      /**
	   *这种方式不会出证书ssl 问题
	   *
	   */

	  public static String doPost(String urlStr ,String jsonParam ,String postType ) {
	        StringBuffer sb = new StringBuffer("");
	        try {
	            //创建连接
	            URL url = new URL(urlStr);
	            HttpsURLConnection connection = (HttpsURLConnection) url
	                    .openConnection();
	            connection.setDoOutput(true);
	            connection.setDoInput(true);
	            connection.setRequestMethod("POST");
	            connection.setUseCaches(false);
	            connection.setInstanceFollowRedirects(true);
		    //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 application/json;charset=utf-8 -> json数据
	            if(postType.equals("json")) {
	            	connection.setRequestProperty("Content-Type",
		                    "application/json;charset=utf-8");
	            }
	            if(postType.equals("form")) {
	            	connection.setRequestProperty("Content-Type",
		                    "application/x-www-form-urlencoded");	
	            }
		        connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            connection.connect();
	            //POST请求
	            DataOutputStream out = new DataOutputStream(
	                    connection.getOutputStream());
	            JSONObject obj = new JSONObject();
	        
	            	   obj= JSONObject.parseObject(jsonParam);	
	                    out.writeBytes(obj.toString());
			            out.flush();
			            out.close();
			          
	            //读取响应
	            BufferedReader reader = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String lines;
	    
	            while ((lines = reader.readLine()) != null) {
	                lines = new String(lines.getBytes(), "utf-8");
	                sb.append(lines);
	            }
	            reader.close();
	            // 断开连接
	            connection.disconnect();
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (UnsupportedEncodingException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
			return sb.toString();
	 
	    }












	/**
     * http get请求
     * @param url 接口url
     * @param token token
     * @return  返回接口数据
     */
    protected static String executeGet(String url, String token) {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
		HttpConnectionParams.setSoTimeout(httpParams, 1000);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		String result = null;
		try {
			HttpGet get = new HttpGet(url);
			// 设置header
			get.setHeader("Authorization", token);
			// 设置类型
			HttpResponse response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值