Android - OkHttp3連線 post應用
引用:compile 'com.squareup.okhttp3:okhttp:3.8.1'
1.基本應用
1.基本應用
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
private static final MediaType MEDIA_TYPE_VIDEO = MediaType.parse("video/*");
private static final OkHttpClient client = new OkHttpClient();
public static String queryJsonPost(String url, JSONObject jsonObj, Boolean hflag) {
String result = null;
Log.d("send_url", url);
String jsonObjStr = "";
try {
if (jsonObj != null) {
jsonObjStr = jsonObj.toString();
} else {
jsonObjStr = "";
}
Log.d("send_data", jsonObjStr);
// 設定連線等時間
new OkHttpClient.Builder()
.connectTimeout(DEFAULT_CONNET_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.MILLISECONDS);
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, jsonObjStr))
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
// result = java.net.URLDecoder.decode(result,"UTF-8");
return result;
}
Log.i("res=", "" + response.body().string());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "異常!";
return result;
} catch (IOException e) {
e.printStackTrace();
result = "異常!";
return result;
}
return null;
}
2.傳送圖片
File mFile = new File(photoPath);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("jsonInput", jsonObjStr)
.addFormDataPart(photoKey, "image.jpg",
RequestBody.create(MEDIA_TYPE_PNG, mFile))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
3.傳送影片
File vdo_mFile = new File(videoPath);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("jsonInput", jsonObjStr)
.addFormDataPart(videoKey,"video.mp4",
RequestBody.create(MEDIA_TYPE_VIDEO,vdo_mFile))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
留言
張貼留言