java使用OKHttp调用接口

1.maven引用


		
    		com.squareup.okhttp3
    		okhttp
    		4.10.0
		

2.java代码

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttp {

	public static void main(String[] args) {
		System.out.println("test");
		okhttp();
	}
	
	public static synchronized void okhttp(){
		String url = "http://wwww.baidu.com";
		//url = "http://192.168.0.102:8081/getSn?sn=123";
		OkHttpClient client = new OkHttpClient();
		MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
		RequestBody requestBody = RequestBody.create(mediaType,"RequestBody");
		Request request = new Request.Builder()
		    .url(url)
		    .post(requestBody)
		    .build();
		Call call = client.newCall(request);
		call.enqueue(new Callback() {
		    public void onFailure(Call call, IOException e) {
				System.out.println("失败");
		    }
		    public void onResponse(Call call, Response response) throws IOException {
		        System.out.println("response=="+response.body().string());
		    }
		});


	}
}

你可能感兴趣的:(java,okhttp,java,android)