okHttp

package net;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp {
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	OkHttpClient okHttpClient = new OkHttpClient();

	public String httpGet(String url) throws IOException {
		Request request = new Request.Builder().url(url).build();
		Response response = okHttpClient.newCall(request).execute();
		return response.body().string();
	}

	public String HttpPost(String url, String json) throws IOException {
		RequestBody requestBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(requestBody).build();
		Response response = okHttpClient.newCall(request).execute();
		return response.body().string();
	}

	public String bowlingJson(String player1, String player2) {
		return "{'winCondition':'HIGH_SCORE'," + "'name':'Bowling'," + "'round':4," + "'lastSaved':1367702411696,"
				+ "'dateStarted':1367702378785," + "'players':[" + "{'name':'" + player1
				+ "','history':[10,8,6,7,8],'color':-13388315,'total':39}," + "{'name':'" + player2
				+ "','history':[6,10,5,10,10],'color':-48060,'total':41}" + "]}";
	}

	// test
	public static void main(String[] args) throws IOException {
		// OkHttp myOkHttp = new OkHttp();
		// String response =
		// myOkHttp.run("https://raw.github.com/square/okhttp/master/README.md");

		// String response = new
		// OkHttp().httpGet("https://raw.github.com/square/okhttp/master/README.md");

		OkHttp okHttp = new OkHttp();

		// 可以直接把参数写在URL里,?name=a&password=123
		// GET
		String responseHttpGet = okHttp.httpGet("https://raw.github.com/square/okhttp/master/README.md");

		// POST
		String json = okHttp.bowlingJson("Jesse", "Jake");
		String responseHttpPost = okHttp.HttpPost("http://www.roundsapp.com/post", json);

		System.out.println(responseHttpGet);
		System.out.println(responseHttpPost);
		// System.out.println( );
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值