我尝试在这里解决的是我的代码。
首先在gradle中添加依赖
编译'com.squareup.okhttp:okhttp:2.6.0'
编译'com.google.code.gson:gson:2.2.4'
解析器.java
public class Parser extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
private String type = "";
private String url = "";
private RequestBody parameter;
private Boolean success = true;
private int requestCode = 0;
private boolean isShowProgressDialog = true;
private ProgressDialog progressDialog;
private String jsonResponse = "";
public GetResponse getResponse = null;
private boolean cancel = false;
private boolean isJsonRequest;
public Parser(Activity activity, String type, String url, RequestBody parameter,boolean isShowProgressDialog,int requestCode) {
this.activity = activity;
this.type = type;
this.url = url;
cancel = false;
this.parameter = parameter;
this.isShowProgressDialog = isShowProgressDialog;
this.requestCode = requestCode;
if (isShowProgressDialog) {
progressDialog = new ProgressDialog(activity);
}
}
/**
* @purpose : this constructor is called when get api called.
* @param activity
* @param type
* @param url
* @param isShowProgressDialog
* @param requestCode
*/
public Parser(Activity activity, String type, String url, boolean isShowProgressDialog, int requestCode) {
this.activity = activity;
this.type = type;
this.url = url;
cancel = false;
this.isShowProgressDialog = isShowProgressDialog;
this.requestCode = requestCode;
if (isShowProgressDialog) {
progressDialog = new ProgressDialog(activity);
}
}
public interface GetResponse {
void TaskFinish(String response, int request, boolean success);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isShowProgressDialog) {
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
@Override
protected Boolean doInBackground(Void... voids) {
if (Common.isOnline(activity)) {
try {
if (type.equalsIgnoreCase(Constant.Type.post)) {
jsonResponse = doPostResponse();
} else if (type.equalsIgnoreCase(Constant.Type.get)) {
jsonResponse = doGetResponse();
}
success = true;
} catch (Exception exp) {
exp.printStackTrace();
success = false;
}
return success;
} else {
success = false;
return success;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (cancel) {
cancel = false;
} else {
if (!result) {
if (isShowProgressDialog) {
if (this.progressDialog.isShowing()) {
this.progressDialog.dismiss();
}
}
} else {
if (isShowProgressDialog) {
if (this.progressDialog.isShowing()) {
this.progressDialog.dismiss();
}
}
if (getResponse != null) {
getResponse.TaskFinish(jsonResponse, requestCode, success);
} else {
Log.i("ApiAccess", "You have not assigned IApiAccessResponse delegate");
}
}
}
}
@Override
protected void onCancelled() {
super.onCancelled();
if (isShowProgressDialog) {
getResponse.TaskFinish(jsonResponse, requestCode, success);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
success = false;
cancel = true;
}
private String doPostResponse() {
OkHttpClient okHttpClient = new OkHttpClient();
Response response;
String mResponse = "";
try {
Request request = new Request.Builder()
.url(url)
.post(parameter)
.build();
okHttpClient.setConnectTimeout(90, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(90, TimeUnit.SECONDS);
okHttpClient.setWriteTimeout(90, TimeUnit.SECONDS);
response = okHttpClient.newCall(request).execute();
mResponse = response.body().string();
Log.i("model.Response Post", "" + mResponse);
} catch (Exception exp) {
exp.printStackTrace();
}
return mResponse;
}
private String doGetResponse() {
OkHttpClient okHttpClient = new OkHttpClient();
Response response;
String mResponse = "";
try {
Request request = new Request.Builder()
.url(url)
.build();
response = okHttpClient.newCall(request).execute();
mResponse = response.body().string();
Log.i("model.Response Get", "" + mResponse);
} catch (Exception exp) {
exp.printStackTrace();
}
return mResponse;
}
public void setjsonRequest(boolean isjsonRequest) {
this.isJsonRequest = isjsonRequest;
}
}
并调用Parser.java
public class Login extends AppCompatActivity implements View.OnClickListener, Parser.GetResponse{
private EditText edtEmailId;
private EditText edtPassword;
private Button btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
findViews();
}
public void findViews() {
edtEmailId = (EditText) findViewById(R.id.edtEmailId);
edtPassword = (EditText) findViewById(R.id.edtPassword);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSubmit:
callRegistration();
break;
default:
break;
}
}
private void callRegistration(){
/*RequestBody formBody = new FormEncodingBuilder()
.add("email_id", edtEmailId.getText().toString().trim())
.add("password", edtPassword.getText().toString().trim())
.build();*/
File filePath1 = new File("image1.jpg");
MultipartBuilder multipartBuilder;
multipartBuilder = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart(Constant.emailId, edtEmailId.getText().toString().trim())
.addFormDataPart(Constant.password, edtPassword.getText().toString().trim());
//send image to server using multipart
multipartBuilder.addFormDataPart(Constant.docDriverLicenceFront, filePath1.getName(), RequestBody.create(MediaType.parse("image/jpeg"), Common.convertFileToByte(filePath1)));
RequestBody formBody = multipartBuilder.build();
Parser parser=new Parser(this, Constant.Type.post,Constant.Url.SIGN_IN,formBody,true,0);
parser.setjsonRequest(false);
parser.getResponse = this;
parser.execute();
}
@Override
public void TaskFinish(String response, int request, boolean success) {
if(request==0){
handleResponse(response);
}
}
private void handleResponse(String output) {
AppLog.LogI(TAG, output);
final Gson gson = new Gson();
try {
SignUpModel login = gson.fromJson(output, SignUpModel.class);
if (login != null) {
if (login.status.equalsIgnoreCase("1")) {
AppLog.LogI(TAG, "Success");
//final LoginModel instance = setLoginModel(login);
//SignUpModel.getInstance().getEmailId();
//Common.passIntent(ThankYouActivity.this, SignInActivity.class);
Toast.makeText(this, "" + login.message, Toast.LENGTH_SHORT).show();
Common.passIntent(this, SignInActivity.class);
finish();
} else {
Toast.makeText(this, "" + login.message, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Common.displayToast(ThankYouActivity.this, getResources().getString(R.string.str_something_went_worng));
}
}
}
}
将文件转换为字节的方法。
public static byte[] convertFileToByte(File file) {
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
} catch (IOException e1) {
e1.printStackTrace();
}
return b;
}