1 /* 2 * Copyright (C) 2014 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.squareup.okhttp.recipes; 17 18 import com.squareup.okhttp.MediaType; 19 import com.squareup.okhttp.MultipartBuilder; 20 import com.squareup.okhttp.OkHttpClient; 21 import com.squareup.okhttp.Request; 22 import com.squareup.okhttp.RequestBody; 23 import com.squareup.okhttp.Response; 24 import java.io.File; 25 import java.io.IOException; 26 27 public final class PostMultipart { 28 /** 29 * The imgur client ID for OkHttp recipes. If you're using imgur for anything 30 * other than running these examples, please request your own client ID! 31 * https://api.imgur.com/oauth2 32 */ 33 private static final String IMGUR_CLIENT_ID = "9199fdef135c122"; 34 private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); 35 36 private final OkHttpClient client = new OkHttpClient(); 37 38 public void run() throws Exception { 39 // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image 40 RequestBody requestBody = new MultipartBuilder() 41 .type(MultipartBuilder.FORM) 42 .addFormDataPart("title", "Square Logo") 43 .addFormDataPart("image", null, 44 RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) 45 .build(); 46 47 Request request = new Request.Builder() 48 .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) 49 .url("https://api.imgur.com/3/image") 50 .post(requestBody) 51 .build(); 52 53 Response response = client.newCall(request).execute(); 54 if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 55 56 System.out.println(response.body().string()); 57 } 58 59 public static void main(String... args) throws Exception { 60 new PostMultipart().run(); 61 } 62 } 63