java調用接口之okhttp

JAVA調用restful接口

目前隨着互聯網微服務的興起,需要通過接口進行服務的傳輸情況越來越多,原始的webservice相對較爲臃腫,常見代表爲aix2,xfire等等。新興的則以restfull標準接口爲代表的例如httpUrlConnection,okhttpclient,Unirest爲代表。

首先先介紹一下httpurlconnection

本對象爲JDK原生支持方法,不用引入任何第三方依賴包。具體代碼如下:

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        OutputStreamWriter out = null;
        try {//注意這裏因爲請求了spring發佈的接口都是以html結尾的。
            URL realUrl = new URL(url+".html");
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設置通用的請求屬性
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4620.400 QQBrowser/9.7.13014.400");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            out = new OutputStreamWriter(connection.getOutputStream(),"utf-8"); 
            // 發送請求參數
            out.write("param="+param);
            // flush輸出流的緩衝
            out.flush();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發送GET請求出現異常!" + e);
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    

接下來介紹一下okhhtp

使用okhttp首先要引入依賴包,pom資源庫增加

		<!-- http請求接口 -->
		<dependency>
		    <groupId>com.squareup.okhttp3</groupId>
		    <artifactId>okhttp</artifactId>
		    <version>4.6.0</version>
		</dependency>

接下來我們看JAVA代碼:

	public static String send(String url, String param) {
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		MediaType mediaType = MediaType.parse("text/plain");
		RequestBody body = RequestBody.create(mediaType, "");
		Request request = new Request.Builder().url(WEB_URL + url + "?" + param).method("POST", body).build();
		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {// 請求成功
				return response.body().string();
			} else {
				return "";
			}
		}catch (IOException e) {//接口請求異常-直接返回空
			e.printStackTrace();
			return "";
		}


	}

對比一下第一個更像是通過瀏覽器抓包給的數據接口的發那個是,尤其對conn.set各種屬性,第二個封裝的較爲簡潔,第二個也是Postman推薦的java代碼的使用方式。

上面代碼佔到ide就能執行,不想動手複製的,也可以直接到這裏去下載:
https://download.csdn.net/download/Himly_Zhang/12440433

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章