Java通过Get请求一个URL。获取网站(也可以说别人的接口)返回的数据 客官°小女子只卖身不卖艺 2022-04-11 11:11 412阅读 0赞 ## 别人给你一个url地址,你通过get请求,得到他返回的数据,这里给你们封装一个方法,需要的话可以直接调用 ## package com.shopping.core.tools; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; 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.HttpPut; import org.apache.http.entity.StringEntity; 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 NpshYanZhengUtil { public static String sendGut(String url, Map<String, Object> map, String encoding) throws ParseException, IOException { String body = ""; CloseableHttpResponse response = null; //client 客户端 ---------------------------- ----- // 创建默认的httpClient实例. CloseableHttpClient client = HttpClients.createDefault(); //GET - 向指定位置获取其内容---------------// 创建httpGet HttpGet httpGet = new HttpGet(url); //StringEntity是httpGet对象的一个实现类 httpGet.setHeader("Content-type", "application/json"); // httpPut.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //客户端执行。获取数据 response = client.execute(httpGet); //通过response里的getEntity()方法获取客户端的返回值,然后return进行返回; HttpEntity entity = response.getEntity(); if (entity != null) { body = EntityUtils.toString(entity, encoding); } // EntityUtils.consume(entity); response.close(); return body; } } 下面给你们一个调用的实例(因为我在这里需要调用别人给的地址,需要他给我返回一个字段,我给他发送的是一个电话,+phone这个phone,是一个手机号,对面返回的数据用data接收,在通过解析转成字符串,就可以得到对面给你发送的数据了,感觉说的很详细了,你们不懂可以留言哦) try { String data = NpshYanZhengUtil.sendGut("http://1*2.1**.*1.1*4:***8/site/queryTenant?phone="+phone,null, null); JSONObject ob = JSON.parseObject(data); //获取里面的数据 String ss = ob.getString("data"); System.out.print("ss"+ss); npsh.setTenant(ss); } catch (Exception e) { e.printStackTrace(); }
还没有评论,来说两句吧...