days[2] = POST JSON数据和Response-网页状态码 ;

实现POST JSON需要先添加依赖库

	<dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.1.0</version>
      </dependency>

直接上代码

import com.alibaba.fastjson.JSON;
import okhttp3.*;

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

public class JsonPoster {
    //规定json的格式
    public static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    public String postContent(String url, Map<String, String> datas) {
        OkHttpClient okHttpClient = new OkHttpClient();
        //数据对象被转换成josn格式
        String param = JSON.toJSONString(datas);
        //post方式提交数据
        RequestBody requestBody = RequestBody.create(JSON_TYPE, param);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
            result = call.execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

状态码

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

import java.io.IOException;

public class GetPage {
    public String getContent (String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
        	//如果不再需要返回文本,可以直接使用code
            Response response = call.execute();
            int code = response.code();
            System.out.println(code);
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "https://www.baidu.com/";
        GetPage getPage = new GetPage();
        String content = getPage.getContent(url);
        System.out.println(content);
    }

}

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

猜你喜欢

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