|
| 1 | +package com.vogella.java.library.okhttp; |
| 2 | + |
| 3 | + |
| 4 | +import java.io.IOException; |
| 5 | + |
| 6 | +import com.squareup.okhttp.MediaType; |
| 7 | +import com.squareup.okhttp.OkHttpClient; |
| 8 | +import com.squareup.okhttp.Request; |
| 9 | +import com.squareup.okhttp.RequestBody; |
| 10 | +import com.squareup.okhttp.Response; |
| 11 | + |
| 12 | + public class TestMain { |
| 13 | + OkHttpClient client = new OkHttpClient(); |
| 14 | + public static final MediaType JSON |
| 15 | + = MediaType.parse("application/json; charset=utf-8"); |
| 16 | + |
| 17 | + String doGetRequest(String url) throws IOException { |
| 18 | + Request request = new Request.Builder() |
| 19 | + .url(url) |
| 20 | + .build(); |
| 21 | + |
| 22 | + Response response = client.newCall(request).execute(); |
| 23 | + return response.body().string(); |
| 24 | + } |
| 25 | + |
| 26 | + // test data |
| 27 | + String bowlingJson(String player1, String player2) { |
| 28 | + return "{'winCondition':'HIGH_SCORE'," |
| 29 | + + "'name':'Bowling'," |
| 30 | + + "'round':4," |
| 31 | + + "'lastSaved':1367702411696," |
| 32 | + + "'dateStarted':1367702378785," |
| 33 | + + "'players':[" |
| 34 | + + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39}," |
| 35 | + + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}" |
| 36 | + + "]}"; |
| 37 | + } |
| 38 | + |
| 39 | + String doPostRequest(String url, String json) throws IOException { |
| 40 | + RequestBody body = RequestBody.create(JSON, json); |
| 41 | + Request request = new Request.Builder() |
| 42 | + .url(url) |
| 43 | + .post(body) |
| 44 | + .build(); |
| 45 | + Response response = client.newCall(request).execute(); |
| 46 | + return response.body().string(); |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) throws IOException { |
| 50 | + |
| 51 | + // issue the Get request |
| 52 | + TestMain example = new TestMain(); |
| 53 | + String getResponse = example.doGetRequest("http://www.vogella.com"); |
| 54 | + System.out.println(getResponse); |
| 55 | + |
| 56 | + |
| 57 | + // issue the post request |
| 58 | + |
| 59 | + String json = example.bowlingJson("Jesse", "Jake"); |
| 60 | + String postResponse = example.doPostRequest("http://www.roundsapp.com/post", json); |
| 61 | + System.out.println(postResponse); |
| 62 | + } |
| 63 | + } |
| 64 | + |
0 commit comments