java使用后台代码访问接口并返回需要的json数据

最近工作中有个任务,就是从一个接口中获取json数据完成页面的动态加载;但是在ajax调用的时候出现了跨域的问题,由于无法修改接口的请求头;所以采用java后台代码通过url获取到数据再返回相关的json数据(考虑到把json全部获取到前台,再遍历的话不仅数据量大而且逻辑会比较复杂),再又ajax调用使用;

1.主要核心:读取url,返回json串;

public String getData(String addess){
    URL url = null;              
    HttpURLConnection httpConn = null;            
    BufferedReader in = null;   
    
    StringBuffer sb = new StringBuffer();   
    try{      
    url = new URL(addess);      
     in = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8") );   
     String str = null;    
     while((str = in.readLine()) != null) {  
      sb.append( str );     
            }     
        } catch (Exception ex) {               
        } finally{    
         try{             
          if(in!=null) { 
        	  
           in.close();     
                }     
            }catch(IOException ex) {      
            }     
        }     
       String  data =sb.toString();     	         
        return data;
}
2.根据业务需要及所请求获取到的json,进行遍历获取相关的newjson数据,主要代码:

//json串转化为json对象
public JSONObject getjson(String data) {
		JSONObject json = JSONObject.fromObject(data);
		return json;
	}

 

getResponse().setHeader("Content-type", "text/html;charset=UTF-8");
//获取到的json串
String s1 = null;  
try {
		s1 = getData("url填入请求的地址");
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
    //异常处理			
		}		
JSONObject jsonobject1 = null;
		JSONArray jsonarray = null;
		//获取第一条json数据的标识符;
		int flag01=1;
		try {
    //json串转化为jsonObj
			jsonobject1 = getjson(s1);
			JSONObject jobjects1= (JSONObject) jsonobject1.get("Response");//获取相关字段
			jsonarray = jobjects1.getJSONArray("result");
		} catch (Exception e2) {
			// TODO Auto-generated catch block
    //异常处理
		}
   //遍历并获取相关数据
		List<String> mnList=new ArrayList();
		for (int i = 0; i < jsonarray.size(); i++) {
			JSONObject data=jsonarray.getJSONObject(i);
			data.get("MON_NAME");
			if(!mnList.contains(data.getString("MON_NAME"))){
				mnList.add(data.getString("MON_NAME"));					
			}
		}
   //遍历mnlist转化为字符串
   StringBuffer sb=new StringBuffer();
		  for (int i = 0; i < mnList.size(); i++) {
			if(i!=mnList.size()-1){
			sb.append(mnList.get(i)+",");}
			else{
				sb.append(mnList.get(i));
			}
		}
   //创建需要的json串,部分代码省略
		String myjsonstr="{\"cname\":\""+sb.toString()+"\",\"dataNum\":\""+dataNum+"\",\"okFlag\":\""+okFlag+"\",\"msg\":\""+msg+"\"}";
		JSONObject myjson = getjson(myjsonstr);	
		JSONArray jarray=new JSONArray();
		jarray.add(jsonobject1);
		jarray.add(myjson);
		try {
			PrintWriter out = getResponse().getWriter();
			out.print(jarray.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

3.最后可以就通过ajax访问获取相关的数据了;



Java中,如果你需要通过HTTP客户端库(如Apache HttpClient、OkHttp等)向API发送请求并设置Content-Type为application/json,以下是一个基本的示例,我们将使用HttpClient库: ```java import org.apache.http.HttpHeaders; 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.HttpClients; public class Main { public static void main(String[] args) throws Exception { // 创建HttpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 创建HttpPost对象,并设置URL HttpPost httpPost = new HttpPost("https://your-api-url.com/api/endpoint"); // 设置Content-Type为application/json httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // 准备要发送的数据,这里以JSON字符串为例 String jsonBody = "{\"key\":\"value\"}"; // 将数据转换为StringEntity StringEntity entity = new StringEntity(jsonBody); httpPost.setEntity(entity); // 执行POST请求 CloseableHttpResponse response = httpClient.execute(httpPost); // ...处理响应... } finally { // 关闭HttpClient连接 httpClient.close(); } } } ``` 在这个例子中,我们首先创建了一个`CloseableHttpResponse`对象,然后设置了请求的Content-Type头部。接着,我们构建了一个包含JSON数据的`StringEntity`,并将它添加到`HttpPost`请求中。最后,我们发送了请求并关闭了连接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值