Home | History | Annotate | Download | only in recipes
      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.OkHttpClient;
     20 import com.squareup.okhttp.Request;
     21 import com.squareup.okhttp.RequestBody;
     22 import com.squareup.okhttp.Response;
     23 import java.io.IOException;
     24 import okio.BufferedSink;
     25 
     26 public final class PostStreaming {
     27   public static final MediaType MEDIA_TYPE_MARKDOWN
     28       = MediaType.parse("text/x-markdown; charset=utf-8");
     29 
     30   private final OkHttpClient client = new OkHttpClient();
     31 
     32   public void run() throws Exception {
     33     RequestBody requestBody = new RequestBody() {
     34       @Override public MediaType contentType() {
     35         return MEDIA_TYPE_MARKDOWN;
     36       }
     37 
     38       @Override public void writeTo(BufferedSink sink) throws IOException {
     39         sink.writeUtf8("Numbers\n");
     40         sink.writeUtf8("-------\n");
     41         for (int i = 2; i <= 997; i++) {
     42           sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
     43         }
     44       }
     45 
     46       private String factor(int n) {
     47         for (int i = 2; i < n; i++) {
     48           int x = n / i;
     49           if (x * i == n) return factor(x) + "  " + i;
     50         }
     51         return Integer.toString(n);
     52       }
     53     };
     54 
     55     Request request = new Request.Builder()
     56         .url("https://api.github.com/markdown/raw")
     57         .post(requestBody)
     58         .build();
     59 
     60     Response response = client.newCall(request).execute();
     61     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
     62 
     63     System.out.println(response.body().string());
     64   }
     65 
     66   public static void main(String... args) throws Exception {
     67     new PostStreaming().run();
     68   }
     69 }
     70