最近因爲一些不得已的緣由,接觸到了OKHttp,提及來也挺Dan疼的,以前同事將生產附件上傳地址配置成了測試地址,還好數量很少,沒有形成太大的影響,何況的是這位同事又離職了,當時只能在心中 默默的問候了他N遍,固然問候完了以後,也不得不繼續數據同步的工做。😭php
OKHTTP官方地址:okHttpjava
本文源地址:一次使用OKHTTP的心痛歷程git
因爲OkHttp官網的介紹十分詳細,這裏只能貼上一段翻譯事後的introduce:github
HTTP是現代應用網絡的一種方式。這就是咱們交換數據和媒體的方式。高效地使用HTTP可讓你的東西更快地加載並節省帶寬。web
OkHttp是一個高效的Http客戶端,在默認的狀況下:數據庫
不過在我使用下來,OkHttp比 apache-http
好用太多,層次結構較直觀。apache
本次場景是將上傳到測試環境的文件信息,下載到本地,而後再上傳到生產環境。json
解決過程以下:api
將錯誤數據從數據庫表中粘貼到本地新建的一個Excel文件中。(畢竟直接鏈接數據庫風險更大)緩存
讀取Excel內的信息,獲取文件地址。
請求文件地址,獲取到流文件信息。
拿到流文件信息,拼接上傳數據,上傳到新的生產環境中。
上傳完成後,獲取到生產環境文件地址。
獲取到生產文件地址的同時,生成更新的SQL語句。
到數據庫中執行SQL語句。
本次使用沒有搭建新的工程,直接再 src/test/java
目錄下新建一個Java類。
引入OKHttp的依賴:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.1</version>
</dependency>
複製代碼
在引入了 okhttp
的jar包後,基本上就能夠開始爲所欲爲的進行本身任意喪心病狂的Http請求了。
好比,它直接同步和異步的請求:
同步GET
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
複製代碼
異步GET
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
}
});
}
複製代碼
Header信息
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
}
複製代碼
POST請求流信息
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers\n");
sink.writeUtf8("-------\n");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
複製代碼
POST請求File信息
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
複製代碼
Post表單提交
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
複製代碼
POST多個Body請求
/** * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running * these examples, please request your own client ID! https://api.imgur.com/oauth2 */
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
複製代碼
由於使用過程當中大多數都是按照官網的例子來進行,因此此次使用的代碼是相似於官方提供的例子,固然也是不太好意思貼出來,哈哈。😁
OkHttp算得上是相見恨晚,以前一遍一遍寫 apache-http
的時候就以爲 apche
有點冗餘,就是想有一個輕量級的,比較好上手,容易懂的http-client,不過如今接觸到了 okhttp,仍是得感謝那位配錯地址的兄弟。😂
以上更多請求例子能夠訪問:OKhttp-Request-example
參考資料: