用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
				       
			          下一篇:
			            OKHttp3使用(POST方式) 
			          
			        
