栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

http工具类,调用第三方接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

http工具类,调用第三方接口

    6月份加入fw做开发,接到了个需求,要使用http工具类调用第三方接口,在网上也找了很多http工具类,但是都不满足我的需求:要么是只传递url和一个参数,要么是传递url和一个map集合;

    我想要的是传递多个参数,并且参数是JSON格式的,于是我改写了其中的代码,最终完成需求:

package com.engine.qnmd.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.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 weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;



public class HttpUtil {

	public static void main(String[] args) throws Exception {
		//获取token
		String token = Token.getToken();
		//测试代码
		JSONObject paramJson2 = new JSONObject();
		paramJson2.put("code", "1234");
		paramJson2.put("statuz", "1");
		String url2="http://";
		String result = doPost(url2, paramJson2, token);
		System.out.println(result);
	}



 
	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    
	 public static String doPost(String url, Map params){
		 BufferedReader in = null;
		 try {
			 // 定义 HttpClient
			 HttpClient client = new DefaultHttpClient();
			 // 实例化 HTTP 方法
			 HttpPost request = new HttpPost();
			 request.setURI(new URI(url));
			 //设置参数
			 List nvps = new ArrayList();
			 for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				 String name = (String) iter.next();
				 String value = String.valueOf(params.get(name));
				 nvps.add(new BasicNameValuePair(name, value));
				 //System.out.println(name +"-"+value);
			 }
			 request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			 HttpResponse response = client.execute(request);
			 int code = response.getStatusLine().getStatusCode();
			 if(code == 200){ //请求成功
				 in = new BufferedReader(new InputStreamReader(response.getEntity()
				 .getContent(),"utf-8"));
				 StringBuffer sb = new StringBuffer("");
				 String line = "";
				 String NL = System.getProperty("line.separator");
				 while ((line = in.readLine()) != null) {
					 sb.append(line + NL);
				 }
				 in.close();
				 return sb.toString();
			 }
			 else{ //
				 log.info("接口调用code:"+code);
				 return null;
			 }
		 }catch(Exception e){
			 e.printStackTrace();
			 return null;
		 }
	 }
	 
	 public static String doPost(String url, JSONObject json, String token) throws Exception {
		 
		 CloseableHttpClient httpclient = HttpClients.createDefault();
		 HttpPost httpPost = new HttpPost(url);// 创建 httpPost

		 httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
		 httpPost.addHeader("Authorization", "Bearer "+token);

		 String charSet = "UTF-8";
		 StringEntity entity = new StringEntity(json.toString(), charSet);
		 httpPost.setEntity(entity);
		 CloseableHttpResponse response = null;
		 try {
			 response = httpclient.execute(httpPost);
			 StatusLine status = response.getStatusLine();
			 int state = status.getStatusCode();
			 log.info("接口调用state:"+state);
			 System.out.println("接口调用state:"+state);
			 if (state == HttpStatus.SC_OK) {
				 HttpEntity responseEntity = response.getEntity();
				 String jsonString = EntityUtils.toString(responseEntity,"UTF-8");
				 return jsonString;
			 }else{
				 return null;
			 }
		 }finally {
			 if (response != null) {
				 try {
					 response.close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
			 try {
				 httpclient.close();
			 } catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
	 }
    
	 public static String doGet(String url) throws Exception {
			URL localURL = new URL(url);
			URLConnection connection = localURL.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
			httpURLConnection.setRequestProperty("Content-Type", "x-www-form-urlencoded");
			InputStream inputStream = null;
			InputStreamReader inputStreamReader = null;
			BufferedReader reader = null;
			StringBuffer resultBuffer = new StringBuffer();
			String tempLine = null;
 
			if (httpURLConnection.getResponseCode() >= 300) {
				throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
			}
 
			try {
				inputStream = httpURLConnection.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream,"utf-8");
				reader = new BufferedReader(inputStreamReader);
 
				while ((tempLine = reader.readLine()) != null) {
					resultBuffer.append(tempLine);
				}
 
			} finally {
 
				if (reader != null) {
					reader.close();
				}
 
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
 
				if (inputStream != null) {
					inputStream.close();
				}
 
			}
			return resultBuffer.toString();
		}
 
}

    我的需求中要用到token,所以我将获取token抽取成一个类,调用方法就可以,大家在使用的过程中,根据要传递的参数的不同可以对方法进行改写,来满足自己的需求。

    这是进入公司拿到的第一个需求,继续加油~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1031483.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号