不得不说真是天下文章一大抄,坑真多,费了好大的劲,才成功搞定android 的http请求。
本来想用人家封装好的,发现都有各种错误,okhttp已经更新了,部分函数也变动了,博客没改,git也没改,
想想还是从基础做起,慢慢封装自己的一些公用类吧。
一、准备工作
到官网下载最新版的okhttp.jar
下载地址:http://square.github.io/okhttp/
拷贝到libs文件夹,右键-Add As Library,这时需要稍等10秒钟左右,AS要构建函数库。
添加权限:
下边就能正式使用了。
二、直接上代码
/**
* 上传文件及参数
*/
private void sendMultipart(){
File sdcache = getExternalCacheDir();
int cacheSize = 10 * 1024 * 1024;
//设置超时时间及缓存,下边都应该这样设置的。
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
OkHttpClient mOkHttpClient=builder.build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "wangshu")//设置post的参数
.addFormDataPart("image", "wangshu.jpg",//如何接收图片,还在研究
RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + "...")
.url("https://***.php")//请求的url
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("InfoMSG", response.body().string());
}
});
}
/**
* 异步下载文件
*/
private void downAsynFile() {
OkHttpClient mOkHttpClient = new OkHttpClient();
String url = "http://***.jpg";
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("/sdcard/123.jpg"));
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
} catch (IOException e) {
Log.i("InfoMSG", "IOException");
e.printStackTrace();
}
Log.d("InfoMSG", "文件下载成功");
}
});
}
/**
* 异步上传文件
*/
private void postAsynFile() {
OkHttpClient mOkHttpClient=new OkHttpClient();
File file = new File("/sdcard/123.txt");
Request request = new Request.Builder()
.url("https://www.****.php")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("InfoMSG",response.body().string());
}
});
}
private void getAsynHttp() {
OkHttpClient mOkHttpClient=new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");
//可以省略,默认是GET请求
requestBuilder.method("GET",null);
Request request = requestBuilder.build();
Call mcall= mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response.cacheResponse()) {
String str = response.cacheResponse().toString();
Log.i("InfoMSG", "cache---" + str);
} else {
response.body().string();
String str = response.networkResponse().toString();
Log.i("InfoMSG", "network---" + str);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 异步http post数据
*/
private void postAsynHttp() {
OkHttpClient mOkHttpClient = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("tel", "10")
.build();
Request request = new Request.Builder()
.url("http://192.168.1.105/interface/index.php")
.post(formBody)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
Log.i("InfoMSG", str);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* post JSON 对象
*/
private void postJSONObj(){
File sdcache = getExternalCacheDir();
int cacheSize = 10 * 1024 * 1024;
//设置超时时间及缓存
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
OkHttpClient mOkHttpClient=builder.build();
RequestBody requestBody1=RequestBody.create(JSON,"\"user\":\"abc\"");
Request request = new Request.Builder()
.url("https://***.php")
.post(requestBody1)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("InfoMSG", response.body().string());
}
});
}
三、服务器接收
$_REQUEST["tel"]//接收post的参数
$GLOBALS["HTTP_RAW_POST_DATA"]//接收json对象
1、上传图片
$act = $_GET["action"];
if ($act == "postimg") {
$content = file_get_contents("php://input");
$imgName = time();
$folder = "images";
$file_dir = $folder . "/" . $imgName . ".jpg";
try {
if (!file_exists($folder)) {//判断目录是否存在
mkdir($folder);//创建目录
}
if ($fp = fopen($file_dir, 'w')) {
if (fwrite($fp, $content)) {//写入文件
fclose($fp);
}
}
} catch(Exception $ex) {
echo "".$ex;
}
echo "图片上传成功";
} 其他用法逐步尝试整理。