public ServerInfoJson getServerInfo(HttpUrl serverUrl, String serverID, String id) throws IOException { // set timeout to 30 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("version", 1); jsonObject.addProperty("command", "get_server_info"); jsonObject.addProperty("stop_when_error", "false"); jsonObject.addProperty("stop_when_success", "false"); jsonObject.addProperty("id", id); jsonObject.addProperty("serverID", serverID); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject)); Request request = new Request.Builder().url(serverUrl).post(requestBody).build(); Response response = client.newCall(request).execute(); InputStream in = response.body().byteStream(); JsonReader reader = null; ServerInfoJson serverInfoJson = null; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); serverInfoJson = gson.fromJson(reader, ServerInfoJson.class); } finally { if (reader != null) { reader.close(); } } if (serverInfoJson != null) { if (serverInfoJson.server != null) { // server info found! return serverInfoJson; } else if (serverInfoJson.sites != null && !serverInfoJson.sites.isEmpty()) { String site = serverInfoJson.sites.get(0); return getServerInfo( new HttpUrl.Builder().scheme("http").host(site).addPathSegment("Serv.php").build(), serverID, id); } } throw new IOException("No server info found!"); }
/** Operation Execution Methods Sync * */ public <T> T execute(String operationId, OperationBody body) { Object input = body.getInput(); if (input instanceof Blob) { // If input is blob or blobs -> use multipart List<MultipartBody.Part> filePart = new ArrayList<>(); RequestBody fbody = RequestBody.create( MediaType.parse(((Blob) input).getMimeType()), ((Blob) input).getFile()); filePart.add( MultipartBody.Part.createFormData(INPUT_PART, ((Blob) input).getFileName(), fbody)); return (T) getResponse(operationId, body, filePart); } else if (input instanceof Blobs) { // If input is blob or blobs -> use multipart List<MultipartBody.Part> fileParts = new ArrayList<>(); for (int i = 0; i < ((Blobs) input).size(); i++) { Blob fileBlob = ((Blobs) input).getBlobs().get(i); RequestBody fbody = RequestBody.create(MediaType.parse(fileBlob.getMimeType()), fileBlob.getFile()); fileParts.add( MultipartBody.Part.createFormData( INPUT_PARTS + String.valueOf(i), fileBlob.getFileName(), fbody)); } return (T) getResponse(operationId, body, fileParts); } else { return (T) getResponse(operationId, body); } }
@Override protected RequestBody postBody(File file) { // 设置请求体 MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); // 封装文件请求体 if (file != null && file.exists()) { String filename = file.getName(); MediaType mediaType = MediaType.parse(guessMimeType(filename)); RequestBody fileBody = RequestBody.create(mediaType, file); builder.addFormDataPart("file", filename, fileBody); } // 封装请求参数 HashMap<String, String> params = new HashMap<>(); addParams(params); if (params != null && !params.isEmpty()) { for (String key : params.keySet()) { builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), RequestBody.create(null, params.get(key))); } } return builder.build(); }
public final class PostFile { public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient.Builder().build(); 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(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } public static void main(String... args) throws Exception { new PostFile().run(); } }
@Test public void kyc_001_create_one_file() throws IOException { final File tmpFile = File.createTempFile("file1", ".jpg"); final BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile)); bw.write("This is the temporary file content"); bw.close(); final RequestBody file1 = RequestBody.create(MediaType.parse("image/jpeg"), tmpFile); final Call<KycEntity> call = service.createKYCRequest(TestSettings.testUserAppUserId, file1); final Response<KycEntity> response = call.execute(); if (response.code() != 201) { System.err.println(response.errorBody().string()); } Assert.assertEquals(response.code(), 201); final KycEntity kyc = response.body(); Assert.assertTrue(kyc.Id > 0); Assert.assertTrue(kyc.VoucherCopies.size() > 0); Assert.assertEquals(kyc.Status, KycStatusEnum.IN_PROGRESS); Assert.assertNotNull(kyc.RequestDate); AttachmentEntity attachment = kyc.VoucherCopies.get(0); Assert.assertTrue(attachment.Id > 0); Assert.assertTrue(attachment.Href != null); Assert.assertTrue(attachment.Name != null); Assert.assertTrue(attachment.ContentType.startsWith("image/")); Assert.assertTrue(attachment.Size > 0); }
public Observable<ApiResponse> uploadImage(long wmId, Uri uri) { File file = new File(uri.getPath()); RequestBody fbody = RequestBody.create(MediaType.parse("application/octet-stream"), file); MultipartBody.Part part = MultipartBody.Part.createFormData("photo", file.getName(), fbody); return apiService.uploadImage(wmId, part).compose(ApiUtils.<ApiResponse>failRequestAsError()); }
@Deprecated private Request buildMultipartFormRequest( String url, String[] fileKeys, File[] files, WeakHashMap<String, String> params, Object... tag) { MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if (params != null) { Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); builder.addFormDataPart(entry.getKey(), entry.getValue()); } } if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); MediaType mediaType = MediaType.parse(guessMediaType(fileName)); builder.addFormDataPart(fileKeys[i], fileName, RequestBody.create(mediaType, file)); } } RequestBody requestBody = builder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.post(requestBody); if (tag.length > 0) { requestBuilder.tag(tag[0]); } return requestBuilder.build(); }
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState == null && mQueryResult == null) { RequestBody shopId = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(getShopId())); File imageFile = new File(mImageFileName); File scaledImageDir = new File(imageFile.getParentFile(), "downsized"); File f = new File(scaledImageDir, imageFile.getName()); // File f = new File(mImageFileName); RequestBody file = RequestBody.create(MediaType.parse("multipart/form-data"), f); String str = FileUtils.readTextFile(new File(mImageMetaFileName)); str = "{\"image\": {\"meta\": " + str + "}}"; RequestBody json = RequestBody.create(MediaType.parse("multipart/form-data"), str); Call<ImageQueryResult> call = RestClient.getSharedInstance().getApiService().getAnnotationsOnImage(file, shopId, json); mProgressDialog = new ProgressDialog(getActivity(), R.style.AppTheme_Dark_Dialog); mProgressDialog.setIndeterminate(true); mProgressDialog.setMessage("Searching..."); mProgressDialog.show(); call.enqueue( new Callback<ImageQueryResult>() { @Override public void onResponse( Call<ImageQueryResult> call, Response<ImageQueryResult> response) { mProgressDialog.hide(); mQueryResult = response.body(); mAnnotationList.clear(); mAnnotationList.addAll(mQueryResult.annotations); mAnnotationAdaptor.notifyDataSetChanged(); mLinearLayoutManager.scrollToPosition(3); drawAnnotations(); } @Override public void onFailure(Call<ImageQueryResult> call, Throwable t) { mProgressDialog.hide(); Toast.makeText(getActivity(), "Failed to fetch annotations.", Toast.LENGTH_LONG) .show(); } }); } }
/** * Uploads a media file and returns the remove URL * * @param file the local file to upload * @return the relative path to media */ public String uploadMedia(File file, String extension) { Map<String, RequestBody> map = new HashMap<>(); RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); map.put("media_file\"; filename=\"" + file.getName(), fileBody); RequestBody extBody = RequestBody.create(MediaType.parse("text/plain"), extension); map.put("extension", extBody); Response<JsonObject> result; try { result = m_api.uploadMedia(getToken(), map).execute(); checkResponse(result); } catch (IOException e) { throw new TembaException("Error uploading media", e); } return result.body().get("location").getAsString(); }
/** Operation Execution Methods Async * */ public void execute(String operationId, OperationBody body, Callback<Object> callback) { Object input = body.getInput(); if (input instanceof Blob) { // If input is blob or blobs -> use multipart Map<String, RequestBody> fbodys = new HashMap<>(); RequestBody fbody = RequestBody.create( MediaType.parse(((Blob) input).getMimeType()), ((Blob) input).getFile()); fbodys.put(INPUT_PART, fbody); super.execute(callback, operationId, body, fbodys); } else if (input instanceof Blobs) { // If input is blob or blobs -> use multipart Map<String, RequestBody> fbodys = new HashMap<>(); for (int i = 0; i < ((Blobs) input).size(); i++) { Blob fileBlob = ((Blobs) input).getBlobs().get(i); RequestBody fbody = RequestBody.create(MediaType.parse(fileBlob.getMimeType()), fileBlob.getFile()); fbodys.put(INPUT_PARTS + String.valueOf(i), fbody); } super.execute(callback, operationId, body, fbodys); } else { super.execute(callback, operationId, body); } }
@Deprecated private Request buildMultipartFormRequest2( String url, String[] fileKeys, File[] files, WeakHashMap<String, String> params, Object... tag) { MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if (params != null) { Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue())); } } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMediaType(fileName)), file); builder.addPart( Headers.of( "Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody); } } RequestBody requestBody = builder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.post(requestBody); if (tag.length > 0) { requestBuilder.tag(tag[0]); } return requestBuilder.build(); }
private static void addFiles(MultipartBody.Builder builder, Pair<String, File>... files) { if (files != null) { RequestBody fileBody; for (int i = 0; i < files.length; i++) { Pair<String, File> filePair = files[i]; String fileKeyName = filePair.first; File file = filePair.second; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); builder.addPart( Headers.of( "Content-Disposition", "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""), fileBody); } } else { throw new IllegalArgumentException("File can not be null"); } }
@Override protected RequestBody buildRequestBody() { if (files == null || files.isEmpty()) { FormBody.Builder builder = new FormBody.Builder(); addParams(builder); return builder.build(); } else { MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); addParams(builder); for (int i = 0; i < files.size(); i++) { PostFormBuilder.FileInput fileInput = files.get(i); RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file); builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody); } return builder.build(); } }
public ServerInfoJson requestTunnel(ServerInfoJson infoJson, String serverID, String id) throws IOException { if (infoJson == null || infoJson.env == null || Util.isEmpty(infoJson.env.control_host)) { return null; } // set timeout to 30 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); final String server = infoJson.env.control_host; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("command", "request_tunnel"); jsonObject.addProperty("version", 1); jsonObject.addProperty("serverID", serverID); jsonObject.addProperty("id", id); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject)); Request request = new Request.Builder() .url(HttpUrl.parse("http://" + server + "/Serv.php")) .post(requestBody) .build(); Response response = client.newCall(request).execute(); JsonReader reader = null; try { InputStream in = response.body().byteStream(); reader = new JsonReader(new InputStreamReader(in, "UTF-8")); return gson.fromJson(reader, ServerInfoJson.class); } finally { if (reader != null) { reader.close(); } } }
/** * post提交Json * * @param tag * @param url * @param headers * @param json * @param postCallBack */ public static void postJson( Object tag, String url, Map<String, String> headers, String json, final PostCallBack postCallBack) { Logger.i(TAG, "postJson url :" + url); setCancel(false); RequestBody postBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); requestBuilder.post(postBody); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "postJson onFailure :" + e.toString()); postCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "postJson onResponse"); postCallBack.onResponse(call, response); } else { Logger.i(TAG, "postJson onError: " + response.code()); postCallBack.onError(response.code()); } } }); }
public void run(String caminho) { final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "file", "imagem.png", RequestBody.create(MEDIA_TYPE_PNG, new File(caminho))) .build(); Request request = new Request.Builder().url(urlfoto).post(requestBody).build(); Response response = null; try { response = client.newCall(request).execute(); if (response.isSuccessful()) { livro.setFoto(response.body().string()); runOnUiThread( new Runnable() { @Override public void run() { Picasso.with(AddAnuncioActivity.this) .load(urlfoto + livro.getFoto()) .placeholder(R.drawable.ic_menu_camera) .error(R.drawable.ic_menu_camera) .into(addImagemLivro); } }); } } catch (IOException e) { e.printStackTrace(); } }
private String uploadImage(String imgUploadURL) { String imgURL = ""; OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "file", "image.png", RequestBody.create( MediaType.parse("image/png"), new File(messageItem.getLocalResource()))) .addFormDataPart("title", "My photo") .build(); Request request = new Request.Builder().url(imgUploadURL).post(requestBody).build(); try { Response response = client.newCall(request).execute(); imgURL = response.body().string(); Log.d("response", "uploadImage:" + imgURL); } catch (IOException e) { e.printStackTrace(); } return imgURL; }
private void submitFeedback( String comment, String user, double rating, String objectID, final AlertDialog customAlertDialog) { final Feedback feedback = new Feedback(); feedback.setUser(user); feedback.setFeedback(comment); feedback.setRating(rating); Gson gson = new Gson(); String requestJSON = gson.toJson(feedback); Log.d("TarotFeedback", "requestJSON :: " + requestJSON); showProgress(getString(R.string.save_progress_1)); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, requestJSON); Request request = null; if (TextUtils.isEmpty(objectID)) { request = new Request.Builder().url(ADD_FEEDBACK).addHeader("x-apikey", API_KEY).post(body).build(); } else { request = new Request.Builder() .url(ADD_FEEDBACK + "/" + objectID) .addHeader("x-apikey", API_KEY) .put(body) .build(); } okHttpClient .newCall(request) .enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread( new Runnable() { @Override public void run() { dismissProgress(); Toast.makeText( TarotFeedbackActivity.this, getString(R.string.update_error_1), Toast.LENGTH_SHORT) .show(); } }); } @Override public void onResponse(Call call, final Response response) throws IOException { if (response.isSuccessful()) { Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { Log.d( "TarotFeedback", responseHeaders.name(i) + ": " + responseHeaders.value(i)); } Gson gson = new Gson(); Feedback feedback = gson.fromJson(response.body().string(), Feedback.class); saveToPreference(feedback, feedback.getObjectId()); runOnUiThread( new Runnable() { @Override public void run() { dismissProgress(); customAlertDialog.dismiss(); Toast.makeText( TarotFeedbackActivity.this, getString(R.string.save_parse_success_1), Toast.LENGTH_SHORT) .show(); } }); } else { Log.d("TarotFeedback", "response :: " + response.isSuccessful()); Log.d("TarotFeedback", "response :: " + response.code()); runOnUiThread( new Runnable() { @Override public void run() { dismissProgress(); Toast.makeText( TarotFeedbackActivity.this, getString(R.string.update_error_1), Toast.LENGTH_SHORT) .show(); } }); } } }); }
@Override public MediaType contentType() { return MediaType.parse(this.contentType); }
/** * Class used to perform Conversations requests. It is recommended to useBVConversationsClient as a * single instance in your app. */ public final class BVConversationsClient { private static final OkHttpClient okHttpClient = BVSDK.getInstance().getOkHttpClient(); static final String conversationsBaseUrl = BVSDK.getInstance().getRootApiUrls().getConversationsApiRootUrl(); private static final MediaType URL_ENCODED = MediaType.parse("application/x-www-form-urlencoded"); /** * @param request QuestionAndAnswerRequest to be sent * @return LoadCall object with the request ready to be sent */ public LoadCallDisplay<QuestionAndAnswerRequest, QuestionAndAnswerResponse> prepareCall( QuestionAndAnswerRequest request) { return createCall(QuestionAndAnswerResponse.class, request); } /** * @param request ProductDisplayPageRequest to be sent * @return LoadCall object with the request ready to be sent */ public LoadCallDisplay<ProductDisplayPageRequest, ProductDisplayPageResponse> prepareCall( ProductDisplayPageRequest request) { return createCall(ProductDisplayPageResponse.class, request); } /** * @param request BulkRatingsRequest to be sent * @return LoadCall object with the request ready to be sent */ public LoadCallDisplay<BulkRatingsRequest, BulkRatingsResponse> prepareCall( BulkRatingsRequest request) { return createCall(BulkRatingsResponse.class, request); } /** * @param request BulkStoreRequest to be sent * @return LoadCall object with the request ready to be sent */ public LoadCallDisplay<BulkStoreRequest, BulkStoreResponse> prepareCall( BulkStoreRequest request) { return createCall(BulkStoreResponse.class, request); } /** * @param request ReviewsRequest to be sent * @return LoadCall object with the request ready to be sent */ public LoadCallDisplay<ReviewsRequest, ReviewResponse> prepareCall(ReviewsRequest request) { return createCall(ReviewResponse.class, request); } public LoadCallDisplay<StoreReviewsRequest, StoreReviewResponse> prepareCall( StoreReviewsRequest request) { return createCall(StoreReviewResponse.class, request); } public interface DisplayLoader< RequestType extends ConversationsDisplayRequest, ResponseType extends ConversationsDisplayResponse> { void loadAsync( LoadCallDisplay<RequestType, ResponseType> call, ConversationsCallback<ResponseType> callback); } public LoadCallSubmission<AnswerSubmissionRequest, AnswerSubmissionResponse> prepareCall( AnswerSubmissionRequest submission) { return createCall(AnswerSubmissionResponse.class, submission); } public LoadCallSubmission<ReviewSubmissionRequest, ReviewSubmissionResponse> prepareCall( ReviewSubmissionRequest submission) { return createCall(ReviewSubmissionResponse.class, submission); } public LoadCallSubmission<StoreReviewSubmissionRequest, StoreReviewSubmissionResponse> prepareCall(StoreReviewSubmissionRequest submission) { return createCall(StoreReviewSubmissionResponse.class, submission); } public LoadCallSubmission<QuestionSubmissionRequest, QuestionSubmissionResponse> prepareCall( QuestionSubmissionRequest submission) { return createCall(QuestionSubmissionResponse.class, submission); } private < RequestType extends ConversationsDisplayRequest, ResponseType extends ConversationsDisplayResponse> LoadCallDisplay<RequestType, ResponseType> createCall( Class<ResponseType> responseTypeClass, RequestType request) { String fullUrl = String.format( "%s%s?%s", conversationsBaseUrl, request.getEndPoint(), request.getUrlQueryString()); Logger.d("url", fullUrl); Request okRequest = new Request.Builder() .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent()) .url(fullUrl) .build(); return new LoadCallDisplay<RequestType, ResponseType>( request, responseTypeClass, okHttpClient.newCall(okRequest)); } private static < RequestType extends ConversationsSubmissionRequest, ResponseType extends ConversationsResponse> LoadCallSubmission<RequestType, ResponseType> createCall( Class<ResponseType> responseTypeClass, RequestType submission) { if (submission.getBuilder().getAction() == Action.Submit) { submission.setForcePreview(true); } return loadCallFromSubmission(responseTypeClass, submission); } static < RequestType extends ConversationsSubmissionRequest, ResponseType extends ConversationsResponse> LoadCallSubmission<RequestType, ResponseType> loadCallFromSubmission( Class<ResponseType> responseTypeClass, RequestType submission) { String fullUrl = String.format("%s%s", conversationsBaseUrl, submission.getEndPoint()); Log.d("url", fullUrl); String json = submission.getUrlQueryString(); RequestBody body = RequestBody.create(URL_ENCODED, json); Request okRequest = new Request.Builder() .post(body) .addHeader("Content-type", "application/x-www-form-urlencoded") .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent()) .url(fullUrl) .build(); return new LoadCallSubmission<RequestType, ResponseType>( submission, responseTypeClass, okHttpClient.newCall(okRequest)); } static < RequestType extends ConversationsSubmissionRequest, ResponseType extends ConversationsResponse> LoadCall<RequestType, ResponseType> reCreateCallWithPhotos( Class<ResponseType> responseTypeClass, RequestType submission, List<Photo> photos) { submission.setPhotos(photos); submission.getBuilder().photoUploads.clear(); submission.setForcePreview(false); LoadCall loadCall = loadCallFromSubmission(responseTypeClass, submission); return loadCall; } static < RequestType extends ConversationsSubmissionRequest, ResponseType extends ConversationsResponse> LoadCall<RequestType, ResponseType> reCreateCallNoPreview( Class<ResponseType> responseTypeClass, RequestType submission) { submission.setForcePreview(false); return loadCallFromSubmission(responseTypeClass, submission); } }
/** Created by _SOLID Date:2016/3/30 Time:15:02 */ public class HttpUtils { public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); private Handler mHandler; private static volatile HttpUtils mInstance; private static final OkHttpClient mOkHttpClient; static { mOkHttpClient = new OkHttpClient() .newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); } private HttpUtils() { mHandler = new Handler(Looper.getMainLooper()); } public static HttpUtils getInstance() { if (mInstance == null) synchronized (HttpUtils.class) { if (mInstance == null) { mInstance = new HttpUtils(); } } return mInstance; } /** * 不会开启异步线程 * * @param request * @return * @throws IOException */ public static Response execute(Request request) throws IOException { return mOkHttpClient.newCall(request).execute(); } /** * 开启异步线程访问网络 * * @param request * @param responseCallback */ public static void enqueue(Request request, okhttp3.Callback responseCallback) { mOkHttpClient.newCall(request).enqueue(responseCallback); } public void loadString(final String url, final HttpCallBack callBack) { new Thread( new Runnable() { @Override public void run() { Request request = new Request.Builder().url(url).build(); try { mHandler.post( new Runnable() { @Override public void run() { callBack.onLoading(); } }); final Response response = execute(request); if (response.isSuccessful()) { // 请求成功 final String result = response.body().string(); mHandler.post( new Runnable() { @Override public void run() { callBack.onSuccess(result); } }); } else { mHandler.post( new Runnable() { @Override public void run() { callBack.onError(new Exception("请求失败")); } }); } } catch (final IOException e) { mHandler.post( new Runnable() { @Override public void run() { callBack.onError(e); } }); } } }) .start(); } /** * post JSON data to server * * @param url * @param json * @param callBack */ public void post(String url, String json, final HttpCallBack callBack) { RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json); Request request = new Request.Builder().url(url).post(body).build(); Response response = null; try { response = mOkHttpClient.newCall(request).execute(); if (response.isSuccessful()) { callBack.onSuccess(response.body().string()); } else { callBack.onError(new Exception("Unexpected code " + response)); } } catch (IOException e) { e.printStackTrace(); callBack.onError(e); } } /** * 加载图片 * * @param url the url of image * @param iv ImageView */ public void loadImage(String url, ImageView iv) { loadImage(url, iv, false); } public void loadImage(String url, ImageView iv, boolean isCenterCrop) { loadImageWithHolder(url, iv, R.drawable.default_load_img, isCenterCrop); } /** * 加载图片 * * @param url the url of image * @param iv ImageView * @param placeholderResID default image */ public void loadImageWithHolder( String url, ImageView iv, int placeholderResID, boolean isCenterCrop) { Picasso.with(SolidApplication.getInstance()) .load(url) .placeholder(placeholderResID) .fit() .into(iv); RequestCreator creator = Picasso.with(SolidApplication.getInstance()) .load(url) .placeholder(R.drawable.default_load_img); if (isCenterCrop) { creator.centerCrop(); } creator.fit().into(iv); } public interface HttpCallBack { void onLoading(); void onSuccess(String result); void onError(Exception e); } }
@Override protected void downloadRemote() throws IOException, HttpException, DavException, ContactsStorageException { App.log.info("Downloading " + toDownload.size() + " contacts (" + MAX_MULTIGET + " at once)"); // prepare downloader which may be used to download external resource like contact photos Contact.Downloader downloader = new ResourceDownloader(collectionURL); // download new/updated VCards from server for (DavResource[] bunch : ArrayUtils.partition( toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) { if (Thread.interrupted()) return; App.log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote.get("text/vcard;version=4.0, text/vcard;charset=utf-8;q=0.8, text/vcard;q=0.5"); String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag; Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVCard(remote.fileName(), eTag, stream, charset, downloader); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davAddressBook().multiget(urls.toArray(new HttpUrl[urls.size()]), hasVCard4); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } AddressData addressData = (AddressData) remote.properties.get(AddressData.NAME); if (addressData == null || addressData.vCard == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(addressData.vCard.getBytes()); processVCard(remote.fileName(), eTag, stream, charset, downloader); } } } }
public class PostRequest { public static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream;charset=utf-8"); public static final MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8"); public static final MediaType MEDIA_TYPE_FORM = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); public static final MediaType MEDIA_TYPE_IMG = MediaType.parse("image/*"); public static final MediaType MEDIA_TYPE_AUDIO = MediaType.parse("audio/*"); private Request.Builder builder = new Request.Builder(); private Headers.Builder headers; private String url; private RequestBody requestBody; private Object tag; private Callback callback; public PostRequest url(String url) { this.url = url; return this; } public PostRequest header(String key, String value) { if (headers == null) { headers = new Headers.Builder(); } headers.set(key, value); return this; } public PostRequest addHeader(String key, String value) { if (headers == null) { headers = new Headers.Builder(); } headers.add(key, value); return this; } public PostRequest cacheControl(CacheControl cacheControl) { String value = cacheControl.toString(); return addHeader("Cache-Control", value); } public PostRequest tag(Object tag) { this.tag = tag; return this; } public PostRequest byteBuilder(byte[] bytes) { requestBody = RequestBody.create(MEDIA_TYPE_STREAM, bytes); return this; } public PostRequest strBuilder(String body) { requestBody = RequestBody.create(MEDIA_TYPE_FORM, body); return this; } public PostRequest jsonBuilder(String body) { requestBody = RequestBody.create(MEDIA_TYPE_JSON, body); return this; } public PostRequest fileBuilder(final File file) { RequestBody body = RequestBody.create(MEDIA_TYPE_STREAM, file); requestBody = new ProgressRequestBody( body, new ProgressListener() { @Override public void onProgress(long bytesRead, long contentLength, boolean done) { if (callback != null) { callback.upload(file.getName(), bytesRead, contentLength, done); } } }); return this; } public PostRequest formBuilder(FormBody.Builder builder) { requestBody = builder.build(); requestBody = new ProgressRequestBody( requestBody, new ProgressListener() { @Override public void onProgress(long bytesRead, long contentLength, boolean done) { if (callback != null) { callback.upload("", bytesRead, contentLength, done); } } }); return this; } public PostRequest multiBuilder(MultipartBody.Builder builder) { requestBody = builder.build(); requestBody = new ProgressRequestBody( requestBody, new ProgressListener() { @Override public void onProgress(long bytesRead, long contentLength, boolean done) { if (callback != null) { callback.upload("", bytesRead, contentLength, done); } } }); return this; } public PostRequest request(RequestBody requestBody) { this.requestBody = requestBody; return this; } public Request create() { builder.url(url); builder.tag(tag); if (headers != null) { builder.headers(headers.build()); } builder.post(requestBody); return builder.build(); } public PostRequest callback(Callback callback) { this.callback = callback; return this; } @Deprecated private Request buildPostFormRequest( String url, WeakHashMap<String, String> params, Object... tag) { FormBody.Builder builder = new FormBody.Builder(); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); builder.add(entry.getKey(), entry.getValue()); } RequestBody formBody = builder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.post(formBody); if (tag.length > 0) { requestBuilder.tag(tag[0]); } return requestBuilder.build(); } public static String guessMediaType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } @Deprecated private Request buildMultipartFormRequest( String url, String[] fileKeys, File[] files, WeakHashMap<String, String> params, Object... tag) { MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if (params != null) { Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); builder.addFormDataPart(entry.getKey(), entry.getValue()); } } if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); MediaType mediaType = MediaType.parse(guessMediaType(fileName)); builder.addFormDataPart(fileKeys[i], fileName, RequestBody.create(mediaType, file)); } } RequestBody requestBody = builder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.post(requestBody); if (tag.length > 0) { requestBuilder.tag(tag[0]); } return requestBuilder.build(); } @Deprecated private Request buildMultipartFormRequest2( String url, String[] fileKeys, File[] files, WeakHashMap<String, String> params, Object... tag) { MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if (params != null) { Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue())); } } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMediaType(fileName)), file); builder.addPart( Headers.of( "Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody); } } RequestBody requestBody = builder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.post(requestBody); if (tag.length > 0) { requestBuilder.tag(tag[0]); } return requestBuilder.build(); } @Deprecated private Request buildStringRequest(String url, String bodyStr, Object... tag) { RequestBody body = RequestBody.create(MEDIA_TYPE_PLAIN, bodyStr); Request.Builder builder = new Request.Builder(); builder.url(url); builder.post(body); if (tag.length > 0) { builder.tag(tag[0]); } return builder.build(); } @Deprecated private Request buildFileRequest( String url, File bodyFile, ProgressListener progressListener, Object... tag) { RequestBody body = RequestBody.create(MEDIA_TYPE_STREAM, bodyFile); ProgressRequestBody progressRequestBody = new ProgressRequestBody(body, progressListener); Request.Builder builder = new Request.Builder(); builder.url(url); builder.post(progressRequestBody); if (tag.length > 0) { builder.tag(tag[0]); } return builder.build(); } @Deprecated private Request buildByteRequest(String url, byte[] bytes, Object... tag) { RequestBody body = RequestBody.create(MEDIA_TYPE_STREAM, bytes); Request.Builder builder = new Request.Builder(); builder.url(url); builder.post(body); if (tag.length > 0) { builder.tag(tag[0]); } return builder.build(); } }
/** * Begin a static scan on FoD * * @param uploadRequest zip file to upload * @return true if the scan succeeded */ @SuppressFBWarnings( value = "REC_CATCH_EXCEPTION", justification = "The intent of the catch-all is to make sure that the Jenkins user and logs show the plugin's problem in the build log.") public boolean startStaticScan(final JobConfigModel uploadRequest) { PrintStream logger = FodUploaderPlugin.getLogger(); PostStartScanResponse scanStartedResponse = null; File uploadFile = uploadRequest.getUploadFile(); try (FileInputStream fs = new FileInputStream(uploadFile)) { byte[] readByteArray = new byte[CHUNK_SIZE]; byte[] sendByteArray; int fragmentNumber = 0; int byteCount; long offset = 0; if (api.getToken() == null) api.authenticate(); if (!uploadRequest.hasAssessmentTypeId() && !uploadRequest.hasTechnologyStack()) { logger.println("Missing Assessment Type or Technology Stack."); return false; } // Build 'static' portion of url String fragUrl = api.getBaseUrl() + "/api/v3/releases/" + uploadRequest.getReleaseId() + "/static-scans/start-scan?"; fragUrl += "assessmentTypeId=" + uploadRequest.getAssessmentTypeId(); fragUrl += "&technologyStack=" + uploadRequest.getTechnologyStack(); fragUrl += "&entitlementId=" + uploadRequest.getEntitlementId(); fragUrl += "&entitlementFrequencyType=" + uploadRequest.getEntitlementFrequencyTypeId(); if (uploadRequest.hasLanguageLevel()) fragUrl += "&languageLevel=" + uploadRequest.getLanguageLevel(); if (uploadRequest.getIsExpressScan()) fragUrl += "&scanPreferenceType=2"; if (uploadRequest.getIsExpressAudit()) fragUrl += "&auditPreferenceType=2"; if (uploadRequest.getRunOpenSourceAnalysis()) fragUrl += "&doSonatypeScan=" + uploadRequest.getRunOpenSourceAnalysis(); if (uploadRequest.getIsRemediationScan()) fragUrl += "&isRemediationScan=" + uploadRequest.getIsRemediationScan(); if (uploadRequest.getExcludeThirdParty()) fragUrl += "&excludeThirdPartyLibs=" + uploadRequest.getExcludeThirdParty(); Gson gson = new Gson(); // Loop through chunks logger.println("TOTAL FILE SIZE = " + uploadFile.length()); logger.println("CHUNK_SIZE = " + CHUNK_SIZE); while ((byteCount = fs.read(readByteArray)) != -1) { if (byteCount < CHUNK_SIZE) { sendByteArray = Arrays.copyOf(readByteArray, byteCount); fragmentNumber = -1; } else { sendByteArray = readByteArray; } MediaType byteArray = MediaType.parse("application/octet-stream"); Request request = new Request.Builder() .addHeader("Authorization", "Bearer " + api.getToken()) .addHeader("Content-Type", "application/octet-stream") // Add offsets .url(fragUrl + "&fragNo=" + fragmentNumber++ + "&offset=" + offset) .post(RequestBody.create(byteArray, sendByteArray)) .build(); // Get the response Response response = api.getClient().newCall(request).execute(); if (response.code() == HttpStatus.SC_FORBIDDEN) { // got logged out during polling so log back in // Re-authenticate api.authenticate(); // if you had to reauthenticate here, would the loop and request not need to be // resubmitted? // possible continue? } offset += byteCount; if (fragmentNumber % 5 == 0) { logger.println( "Upload Status - Fragment No: " + fragmentNumber + ", Bytes sent: " + offset + " (Response: " + response.code() + ")"); } if (response.code() != 202) { String responseJsonStr = IOUtils.toString(response.body().byteStream(), "utf-8"); // final response has 200, try to deserialize it if (response.code() == 200) { scanStartedResponse = gson.fromJson(responseJsonStr, PostStartScanResponse.class); logger.println( "Scan " + scanStartedResponse.getScanId() + " uploaded successfully. Total bytes sent: " + offset); return true; } else if (!response .isSuccessful()) { // There was an error along the lines of 'another scan in progress' // or something logger.println("An error occurred during the upload."); GenericErrorResponse errors = gson.fromJson(responseJsonStr, GenericErrorResponse.class); if (errors != null) logger.println( "Package upload failed for the following reasons: " + errors.toString()); return false; // if there is an error, get out of loop and mark build unstable } } response.body().close(); } // end while } catch (Exception e) { e.printStackTrace(logger); return false; } return false; }