使用接口回调解析数据并下载网络图片

Posted llguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用接口回调解析数据并下载网络图片相关的知识,希望对你有一定的参考价值。

package DemoBook;

import mode.CookBook;

public class Demobook {
	// 向网络回去json数据,通过接口回调
	// gson解析数据
	// 依据pic图片地址,下载图片存入磁盘中
	// gson解析数据
	public static void main(String[] args) {
		String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";

		new DownLoadThread(path, new Mycallback() {

			@Override
			public void printCook(CookBook cb) {
				// 数据下载,而且解析完毕的
				System.out.println(cb);

			}
		}).start();

	}
}

package DemoBook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.google.gson.Gson;

import mode.CookBook;
import mode.FoodMenu;

/*
 * 开启线程,下载网络数据
 * 
 */
public class DownLoadThread extends Thread {
	private String path;

	private Mycallback callBack;

	public DownLoadThread(String path, Mycallback callBack) {
		// TODO Auto-generated constructor stub
		this.path = path;
		this.callBack = callBack;
	}

	@Override
	public void run() {

		// 下载json数据
		String json = HttpUtil.getStringResultByOkHttp(path);
		// 解析数据
		CookBook cb = new Gson().fromJson(json, CookBook.class);

		// 得到FoodMenu
		ArrayList<FoodMenu> list = cb.getData();

		for (FoodMenu foodMenu : list) {
			String pic = foodMenu.getPic();

			byte[] data = HttpUtil.getByteResultByOkHttp(pic);

			String picName = pic.substring(pic.lastIndexOf("/") + 1);
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream("d:/cook/" + picName);
				fos.write(data);
				System.out.println(picName + "下载完毕");

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		// 通过接口回调,将解析后的数据放回

		callBack.printCook(cb);

	}
}

package DemoBook;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtil {

	/**
	 * 通过HttpConnection  的   Get方式获取信息
	 * 
	 * @param path
	 *            请求地址
	 * @return byte[]
	 */
	public static byte[] getResult(String path) {
		HttpURLConnection conn = null;

		ByteArrayOutputStream baos = null;

		InputStream is = null;
		try {
			// 1, 得到URL对象
			URL url = new URL(path);

			// 2, 依据URL对象打开HttpUrlConnection对象
			conn = (HttpURLConnection) url.openConnection();

			// 3, 设置请求方式(能够不写, 默认"GET",能够指定"POST",必须大写 )
			conn.setRequestMethod("GET");
			// 连接
			conn.connect();

			baos = new ByteArrayOutputStream();

			// 4, 获取响应
			if (conn.getResponseCode() == 200) {
				is = conn.getInputStream();

				byte[] buffer = new byte[1024];

				int len = 0;

				while ((len = is.read(buffer)) != -1) {

					baos.write(buffer, 0, len);
				}

				return baos.toByteArray();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();// 断开连接
			}
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	/**
	 * 通过HttpConnection  的   Get方式获取信息
	 * @param path
	 * @return String
	 */
	public static String getResultStr(String path)
	{
		HttpURLConnection conn = null;
		InputStream is =null;
		BufferedReader br = null;
		String str = null;
		try {
			
			URL url = new URL(path);
			
			conn = (HttpURLConnection) url.openConnection();
			
			if(conn.getResponseCode()==200)
			{
				is = conn.getInputStream();
				
				br = new BufferedReader(new InputStreamReader(is));
				
				str = br.readLine();
				
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(conn!=null)
			{
				conn.disconnect();
			}
			if(is!=null)
			{
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(br!=null)
			{
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return str;
	}
	
	/**
	 * 通过HttpUrlConnection 的 post方式提交数据 , 获取响应的信息
	 * 
	 * @param path  路径
	 * @param data  參数     "useName=abc&usePwd=123"  没有?
	 * @return String 
	 */
	public static String postData(String path,String data)
	{
		String str = null;
		HttpURLConnection conn = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader br = null;
		
		try {
			URL url = new URL(path);
			
			conn = (HttpURLConnection)url.openConnection();
			
			conn.setRequestMethod("POST");
			
			conn.setDoOutput(true);
			
			 os = conn.getOutputStream();
			os.write(data.getBytes());
			os.flush();
			
			if(conn.getResponseCode() == 200)
			{
				is = conn.getInputStream();
				
				br = new BufferedReader(new InputStreamReader(is));
				
				str = br.readLine();
				
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			if(conn!=null)
			{
				conn.disconnect();
			}
			if(os!=null)
			{
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			if(is!=null)
			{
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			if(br!=null)
			{
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
		
		return str;
	}
	
	/**
	 * 通过okHttp获取数据
	 * 
	 * @param path
	 * @return byte[]
	 */
	public static byte[] getByteResultByOkHttp(String path)
	{
		byte[] data= null;
		
		try
		{
			
			OkHttpClient client = new OkHttpClient();
			
			Request request = new Request.Builder().url(path).build();

			// 请求数据,得到响应信息
			Response response = client.newCall(request).execute();

			if (response.isSuccessful()) {
				
				data = response.body().bytes();

				return data;
			}
			
		}catch(Exception exception)
		{
			exception.printStackTrace();
		}
		
		return data;
	}
	
	/**
	 *  通过okHttp获取数据
	 * @param path
	 * @return String
	 */
	public static String getStringResultByOkHttp(String path)
	{
		String data= null;
		
		try
		{
			
			OkHttpClient client = new OkHttpClient();
			
			Request request = new Request.Builder().url(path).build();

			// 请求数据,得到响应信息
			Response response = client.newCall(request).execute();

			if (response.isSuccessful()) {
				
				data = response.body().string();

				return data;
			}
			
		}catch(Exception exception)
		{
			exception.printStackTrace();
		}
		
		return data;
	}
	
	/**
	 * 通过okHttp下载图片, 接口回调的方式返回下载的结果
	 * @param path
	 * @param callBack
	 */

}

package DemoBook;

import mode.CookBook;

/**
 * 网络下砸json的回调接口
 * @author Administrator
 *
 */
public interface Mycallback {

public void printCook(CookBook cb);
	

}

package mode;

import java.util.ArrayList;

public class CookBook {
private int ret;

private ArrayList<FoodMenu> data;

public int getRet() {
	return ret;
}

public void setRet(int ret) {
	this.ret = ret;
}

public ArrayList<FoodMenu> getData() {
	return data;
}

public void setData(ArrayList<FoodMenu> data) {
	this.data = data;
}

@Override
public String toString() {
	return "CookBook [ret=" + ret + ", data=" + data + "]";
}

public CookBook(int ret, ArrayList<FoodMenu> data) {
	super();
	this.ret = ret;
	this.data = data;
}


	
}

package mode;

public class FoodMenu {
private int id;
private String title;
private String  pic;
private String collect_num;
private String food_str;
private int num;
@Override
public String toString() {
	return "FoodMenu [id=" + id + ", title=" + title + ", pic=" + pic + ", collect_num=" + collect_num + ", food_str="
			+ food_str + ", num=" + num + "]";
}
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getTitle() {
	return title;
}
public void setTitle(String title) {
	this.title = title;
}
public String getPic() {
	return pic;
}
public void setPic(String pic) {
	this.pic = pic;
}
public String getCollect_num() {
	return collect_num;
}
public void setCollect_num(String collect_num) {
	this.collect_num = collect_num;
}
public String getFood_str() {
	return food_str;
}
public void setFood_str(String food_str) {
	this.food_str = food_str;
}
public int getNum() {
	return num;
}
public void setNum(int num) {
	this.num = num;
}
public FoodMenu(int id, String title, String pic, String collect_num, String food_str, int num) {
	super();
	this.id = id;
	this.title = title;
	this.pic = pic;
	this.collect_num = collect_num;
	this.food_str = food_str;
	this.num = num;
}


}

以上是关于使用接口回调解析数据并下载网络图片的主要内容,如果未能解决你的问题,请参考以下文章

UE4实用技能写一个异步回调的蓝图接口

接口回调封装

如何使用接口将活动回调返回到片段

片段 getActivity() 与接口回调?

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题