用okhttp发送get和post请求

依赖导入

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

get and post

import okhttp3.*;

import java.io.IOException;
import java.util.Objects;

public class main {
    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        //get方法
        Request request1 = new Request.Builder().url("https://www.baidu.com").build();

        //post方法
        RequestBody requestBody = new FormBody.Builder().add("account","admin").build();
        Request request2 = new Request.Builder().url("https://www.baidu.com").post(requestBody).build();

        Response response = client.newCall(request1).execute();
        String resource = Objects.requireNonNull(response.body()).string();
        System.out.println(resource);
    }
}

带json对象的post

import okhttp3.*;

import java.io.IOException;
import java.util.Objects;

public class main {
    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();
        String json = "{"perception": {"inputText": {"text": "你好"}},"userInfo": {"apiKey": "edc59a11ad644bd0a511d9f1c88c1b5c","userId": "1" }}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder().url("https://openapi.tuling123.com/openapi/api/v2").post(requestBody).build();
        Response response = client.newCall(request).execute();
        String responseData = Objects.requireNonNull(response.body()).string();
        System.out.println(responseData);
    }
}

解析json对象

导入依赖

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>
JSONArray array = new JSONArray(json);		//将json字符串转换为json列表对象
array.getJSONArray(i);						//取json列表中的第i个json并将其作为json列表对象
array.getJSONObject(i);						//取json列表中的第i个json并将其作为json对象
jsonObject.getType("key")			//将该json对象下的key匹配的值返回(Type取值为String,Double,Boolean等)
//json=“{"information":{"name":"t","age":19},"list":[{"name":"yy","age":18},{"name":"hhj","age":20}]}”
String json = "{"information":{"name":"t","age":19},"list":[{"name":"yy","age":18},{"name":"hhj","age":20}]}";
JSONObject s1 = new JSONObject(json); 
//s1={"information":{"name":"t","age":19},"list":[{"name":"yy","age":18},{"name":"hhj","age":20}]}
JSONObject s2 = s1.getJSONObject("information");//{"name":"t","age":19}
JSONArray a1 = s1.getJSONArray("list");//[{"name":"yy","age":18},{"name":"hhj","age":20}]
JSONObject s3 = a1.getJSONObject(0);//{"name":"yy","age":18}
String s4 = s3.getString("name");//yy
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值