android網(wǎng)絡(luò)框架之OKhttp[1]一個(gè)處理網(wǎng)絡(luò)請(qǐng)求的開源項(xiàng)目,是安卓端最火熱的輕量級(jí)框架,由移動(dòng)支付[Squar(http://baike.baidu.com/item/Square/65870)公司貢獻(xiàn)(該公司還貢獻(xiàn)了Picasso)[2]用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,現(xiàn)在已經(jīng)打不出來)
下載地址:okhttp ,要翻墻下載裹芝,必須下載okhttp以及okio兩個(gè)jar包酒唉。
示例代碼:
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 利用okhtto實(shí)現(xiàn)發(fā)送網(wǎng)絡(luò)請(qǐng)求
* @author zhaotong
*
*/
public class ServiceTools {
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client=new OkHttpClient();
//發(fā)送post請(qǐng)求
public static String postTargetData(String url ,String content )
{
String result=null;
RequestBody body=RequestBody.create(JSON,content);
Request request=new Request.Builder().url(url).post(body).build();
Response res=null;
try {
res = client.newCall(request).execute();
result=res.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//發(fā)送get請(qǐng)求
public static String getTargetData(String url)
{
String result=null;
Request request=new Request.Builder().url(url).build();
Response res=null;
try {
res=client.newCall(request).execute();
result=res.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}