//首先导入需要的清单文件 依赖
//别忘了添加依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
//封装okhttp
public interface Api {
boolean ISONLINE = true;
String DEV = "http://169.27.23.105";
public static String ONLINE = "http://120.27.23.105";
public static String HOST = ISONLINE ? ONLINE : DEV;
public static String Login = HOST + "/user/login";
public static String REGISTER = HOST + "/user/reg";
public static String CATAGORY = HOST + "/product/getCatagory";
public static String PRODUCT_CATAGORY = HOST + "/product/getProductCatagory?cid=%s";
public static String PRODUCT_CATAGORY_LIST = HOST + "/product/getProducts";
}
import android.util.Log;
import java.io.File;
import java.util.Map;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by peng on 2017/12/1.
*/
public class OkHttpUtils {
private static OkHttpUtils okHttpUtils;
private final OkHttpClient client;
private OkHttpUtils() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
}
public static OkHttpUtils getOkHttpUtils() {
if (okHttpUtils == null) {
synchronized (OkHttpUtils.class) {
if (okHttpUtils == null) {
okHttpUtils = new OkHttpUtils();
}
}
}
return okHttpUtils;
}
/**
* GET请求
*
* @param url
* @param callback
*/
public void doGet(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
/**
* POST请求
*
* @param url
* @param params
* @param callback
*/
public void doPost(String url, Map params, Callback callback) {
if (params == null) {
throw new RuntimeException("参数为空了");
}
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
Log.e("OkHttpUtils", "请求地址:" + url + " 请求的参数:");
FormBody formBody = builder.build();
Request request = new Request.Builder().url(url).post(formBody).build();
client.newCall(request).enqueue(callback);
}
public void uploadFile(String url, Map params, Callback callback) {
if (params == null) {
throw new RuntimeException("参数为空了");
}
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (Object key : params.keySet()) {
if (params.get(key) instanceof String) {//uid
builder.addFormDataPart(key.toString(), params.get(key).toString());
} else if (params.get(key) instanceof File) {//File
File file = (File) params.get(key);
//image/jpeg jpg png
builder.addFormDataPart(key.toString(), file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
}
}
RequestBody body = builder.build();
Log.e("OkHttpUtils", "请求地址:" + url + " 请求的参数:");
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(callback);
}
public void upload(String url, Map params, Callback callback) {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (String key : params.keySet()) {
Object obj = params.get(key);
if (obj instanceof String) {
builder.addFormDataPart(key, obj.toString());
} else if (obj instanceof File) {
File file = (File) obj;
builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file));
}
}
MultipartBody body = builder.build();
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(callback);
}
}
public interface OnNetListener {
public void onSuccess(T t);
public void onFailure(Exception e);
}
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.i("LoggingInterceptor", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.i("LoggingInterceptor", String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
//布局
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import bwie.com.day10_1510d.net.OkHttpUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView mIv;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler =new Handler();
initView();
}
private void initView() {
mIv = (ImageView) findViewById(R.id.iv);
mIv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.iv) {
uploadFile();
}
}
private void uploadFile(){
File externalStorageDirectory = Environment.getExternalStorageDirectory();
String filePath = externalStorageDirectory.getAbsolutePath()+"/b.jpg";
File file =new File(filePath);
Map params = new HashMap<>();
params.put("uid","71");
params.put("file",file);
OkHttpUtils.getOkHttpUtils().upload("https://www.zhaoapi.cn/file/upload",params,new Callback(){
@Override
public void onFailure(Call call, IOException e) {
showMsg(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
showMsg(body.string());
}
});
}
private void showMsg(final String msg){
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
//显示图片
File externalStorageDirectory = Environment.getExternalStorageDirectory();
String filePath = externalStorageDirectory.getAbsolutePath()+"/b.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mIv.setImageBitmap(bitmap);
}
});
}
}