days[3] = Response - 非文本文件和JSON格式输出 ;

非文本文件的类型太多了,除了txt都是的。。。
我就以下载图片为例吧,下载一个csdn的logo的图片(希望审核能过[狗头]狗头保命)

import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class GetPage {
    public byte[] getImage (String url) {
        byte[]bytes = null;
        try {
            bytes = new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute().body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static void main(String[] args) {
        String url = "https://csdnimg.cn/cdn/content-toolbar/csdn-logo_.png?v=20190924.1";
        GetPage getPage = new GetPage();
        byte[]data = getPage.getImage(url);
        try {
            File file = new File("csdn_logo_.png");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

csdn别打我

在这里插入图片描述

JSON格式输出:
这个东西和之前的get请求似乎没多大区别,就是在主方法接收到数据之后加了一个JSON转换


import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;
import java.util.Map;

public class GetPage {
    public String getContent (String url) {
        String result = null;
        try {
            result = new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "这里输入地址";
        GetPage getPage = new GetPage();
        String content = getPage.getContent(url);
        Map contentObj = JSON.parseObject(content,Map.class);
        System.out.println(contentObj);
    }
}

发布了28 篇原创文章 · 获赞 13 · 访问量 3573

猜你喜欢

转载自blog.csdn.net/weixin_46192593/article/details/105115957