当前位置: 首页 > 后端技术 > Java

Java获取第三方接口数据

时间:2023-04-02 01:46:16 Java

HttpClient连接org.apache.httpcomponentshttpclient4.4packagecom.util;导入java.io.IOException;导入java.io.UnsupportedEncodingException;导入java.net.URLEncoder;导入java.util.Map;导入org.apache.http.HttpResponse;导入org.apache.http.auth.AuthScope;导入org.apache.http.auth.UsernamePasswordCredentials;导入org.apache.http.client.CredentialsProvider;导入org.apache.http.client.methods.HttpDelete;导入org.apache.http.client.methods.HttpGet;导入org.apache.http.client.methods.HttpPost;导入org.apache.http.client.methods.HttpPut;导入org.apache.http.client.methods.HttpRequestBase;导入org.apache.http.client.protocol.HttpClientContext;导入org.apache.http.entity.StringEntity;导入org.apache.http.impl.client.BasicCredentialsProvider;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.params.CoreConnectionPNames;importorg.apache.http.util.EntityUtils;/***

*功能:httpClient访问远程接口工具类*Date:March17,201511:19:21AM*
*/@SuppressWarnings("deprecation")publicclassHttpClientUtil{/***
*方法体描述:发起一个向远程接口请求,返回字符串类型结果*@paramurl接口地址*@paramrequestMethod请求类型*@paramparams传参*@returnString返回结果*
*/publicstaticStringhttpRequestToString(Stringurl,StringrequestMethod,Mapparams,String...auth){//接口返回结果StringmethodResult=null;尝试{字符串参数="";布尔hasParams=false;//将参数集合拼接成特定的格式,比如name=zhangsan&age=24for(Stringkey:params.keySet()){Stringvalue=URLEncoder.encode(params.得到(密钥),“UTF-8”);参数+=键+"="+值+"&";有参数=真;}if(hasParams){parameters=parameters.substring(0,parameters.length()-1);}//是否为GET方式请求booleanisGet="get".equalsIgnoreCase(requestMethod);booleanisPost="post".equalsIgnoreCase(requestMethod);booleanisPut="put".equalsIgnoreCase(requestMethod);booleanisDelete="delete".equalsIgnoreCase(requestMethod);//创建HttpClient连接对象DefaultHttpClientclient=newDefaultHttpClient();HttpRequestBase方法=null;如果(isGet){网址+=“?”+参数;方法=新的HttpGet(url);}elseif(isPost){method=newHttpPost(url);HttpPostpostMethod=(HttpPost)方法;StringEntity实体=newStringEntity(参数);postMethod.setEntity(实体);}elseif(isPut){method=newHttpPut(url);HttpPutputMethod=(HttpPut)方法;StringEntity实体=newStringEntity(参数);putMethod.setEntity(实体);}elseif(isDelete){url+="?"+参数;方法=新的HttpDelete(url);}method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,6000);//设置参数类型method.addHeader("Content-Type","application/x-www-form-urlencoded");//httpClient本地上下文HttpClientContextcontext=null;if(!(auth==null||auth.length==0)){Stringusername=auth[0];字符串密码=授权[1];用户名密码信用ntialscredt=newUsernamePasswordCredentials(用户名,密码);//凭证提供者CredentialsProviderprovider=newBasicCredentialsProvider();//凭证的匹配范围provider.setCredentials(AuthScope.ANY,credt);context=HttpClientContext.create();上下文.setCredentialsProvider(提供者);}//访问接口,返回状态码HttpResponseresponse=client.execute(method,context);//返回状态码200,则访问接口成功if(response.getStatusLine().getStatusCode()==200){methodResult=EntityUtils.toString(response.getEntity());}client.close();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}返回方法结果;}}连接工具类/***
*功能:httpUrlConnection访问远程接口工具*Date:March17,201511:19:21AM*
*/publicclassHttpUrlConnectionUtil{/***
*方法体说明:向远程接口发起请求,返回字符串类型结果*@paramurl接口地址*@paramrequestMethod请求方法*@paramparams传递参数关键点:参数值需要用Base64转码*@returnStringreturnresult*
*/publicstaticStringhttpRequestToString(Stringurl,StringrequestMethod,Mapparams){Stringresult=null;try{InputStreamis=httpRequestToStream(url,requestMethod,params);byte[]b=newbyte[is.available()];is.read(b);结果=新字符串(b);}catch(IOExceptione){e.printStackTrace();}返回结果;}/***
*方法体说明:向远程接口发起请求,返回字节流类型结果*作者:itar*日期:2015-03-1711:20:25AM*@paramurl接口地址*@paramrequestMethod请求方法*@paramparams传递参数关键点:参数值需要进行Base64转码*@returnInputStream返回结果*
*/publicstaticInputStreamhttpRequestToStream(Stringurl,StringrequestMethod,Mapparams){InputStreamis=null;尝试{字符串参数="";布尔hasParams=false;//将参数集拼接成特定的格式,比如name=zhangsan&age=24for(Stringkey:params.keySet()){Stringvalue=URLEncoder.encode(params.get(key),"UTF-8");参数+=键+"="+值+"&";有参数=真;}if(hasParams){parameters=parameters.substring(0,parameters.length()-1);}//请求方法是否为getbooleanisGet="get".equalsIgnoreCase(requestMethod);//请求方法是否为postbooleanisPost="post".equalsIgnoreCase(requestMethod);if(isGet){url+="?"+参数;}网址u=新网址(url);HttpURLConnectionconn=(HttpURLConnection)u.openConnection();//请求参数类型(使用restletframeworkFramework时为了兼容,必须设置Content-Type为""空)conn.setRequestProperty("Content-Type","application/octet-stream");//conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//设置连接超时时间conn.setConnectTimeout(50000);//设置读取返回内容的超时时间conn.setReadTimeout(50000);//设置输出到HttpURLConnection对象,因为post方法会将请求参数放在http文本中,所以需要设置为true,默认为falseif(isPost){conn.setDoOutput(true);}//设置从HttpURLConnection对象中读取,默认为trueconn.setDoInput(true);//设置是否使用缓存,post方法不能使用缓存if(isPost){conn.setUseCaches(false);}//设置请求方式,默认为GETconn.setRequestMethod(requestMethod);//post方法需要将传递的参数输出到conn对象if(isPost){DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());dos.writeBytes(参数);dos.flush();dos.close();}//从HttpURLConnection对象中读取响应消息//执行这条语句时正式发起请求is=conn.getInputStream();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();返回是;}}servicepublicinterfaceTestService{voidselectTest();voidselectPost();}serviceImplImplement@ServicepublicclassTestServiceImplimplementsTestService{@OverridepublicvoidselectTest(){//url对应接口Stringurl="http://127.0.0.1:1313/test/get";系统em.out.println(url);System.out.println("------------------------");//map存储受限内容HashMapmap=newHashMap<>();Stringget=HttpUrlConnectionUtil.httpRequestToString(url,"GET",map);System.out.println(get);System.out.println("--------------------");}@OverridepublicvoidselectPost(){//urlinterfaceStringurl="http://127.0.0.1:1313/test/post/lll";System.out.println(url);System.out.println("------------------------");//map存储限制ContentHashMapmap=newHashMap<>();Stringpost=HttpUrlConnectionUtil.httpRequestToString(url,"POST",map);System.out.println(post);System.out.println("--------------------");}}控制层调用@RestControllerpublicclassTestController{@AutowiredprivateTestServicetestService;@GetMapping("test")publicvoidtest01(){testService.selectTest();;}@GetMapping("test/post")publicvoidtest02(){testService.selectPost();}}调用数据成功