1. 程式人生 > >java 利用OKHttp進行get和post訪問

java 利用OKHttp進行get和post訪問

公司業務需求,需要呼叫API,裡面涉及到http的訪問請求,這裡用到了http的一個訪問的框架,自己寫的工具類如下:

package com.handkoo.util;

import java.io.IOException;

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

/**
 * 利用okhttp進行get和post的訪問
 * 
 * @author cp
 *
 */
public class OKHttpUtil {

	/**
	 * 發起get請求
	 * 
	 * @param url
	 * @return
	 */
	public static String httpGet(String url) {
		String result = null;
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(url).build();
		try {
			Response response = client.newCall(request).execute();
			result = response.body().string();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 傳送httppost請求
	 * 
	 * @param url
	 * @param data  提交的引數為key=value&key1=value1的形式
	 * @return
	 */
	public static String httpPost(String url, String data) {
		String result = null;
		OkHttpClient httpClient = new OkHttpClient();
		RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
		Request request = new Request.Builder().url(url).post(requestBody).build();
		try {
			Response response = httpClient.newCall(request).execute();
			result = response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}

okhttp的官網:http://square.github.io/okhttp/  

需要引入okhttp 和okio的兩個jar包