我在android中创建了一个表单,其中一些参数就像一些edittextxs和一个ImageView,我必须将所有值发送到服务器,我已经尝试了这么久,并且已经使用了这么多代码,但我我没有得到问题,为什么它没有上传到服务器,请看我的代码和哪里是错误,如果可能请编辑它...保存我,谢谢大家。我的代码如下: 的 ChangeProfilePicAPI
package com.epe.yehki.backend;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONObject;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Log;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
import android.content.Context;
import android.os.AsyncTask;
public class ChangeProfilePicAPI extends AsyncTask<Void, Void, Void> {
public String customer_id;
public String product_name;
public String category_id;
public String expire_time;
public String detail_desc;
public String esti_ordr_qty;
public String esti_ordr_qty_unit;
public String filename;
public String image;
public Context context;
public ResponseListener responseListener;
public int serverResponseCode = 0;
public HttpURLConnection conn = null;
public InputStream is = null;
public int isError = 0;
public String response = null;
public ChangeProfilePicAPI(Context context, String customer_id, String product_name, String category_id, String expire_time, String detail_desc, String esti_ordr_qty, String esti_ordr_qty_unit,
String filename, String image, ResponseListener responseListener) {
this.context = context;
this.responseListener = responseListener;
this.customer_id = customer_id;
this.product_name = product_name;
this.category_id = category_id;
this.expire_time = expire_time;
this.detail_desc = detail_desc;
this.esti_ordr_qty = esti_ordr_qty;
this.esti_ordr_qty_unit = esti_ordr_qty_unit;
this.filename = filename;
this.image = image;
}
@Override
protected Void doInBackground(Void... params) {
String upLoadServerUri = null;
DataOutputStream dos = null;
FileInputStream fileInputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2 * 1024;
File sourceFile = null;
JSONObject jobj = null;
byte b[] = null;
try {
upLoadServerUri = Const.API_BUYING_REQUEST;
// sourceFile = new File(Const.DIR_USER + "/" + fileName);
if (this.image != null) {
sourceFile = new File(image);
}
System.out.println("::::::::::::::::::::::my file path:::::::::" + image);
if (sourceFile != null && !sourceFile.isFile()) {
this.isError = -1;
this.response = "Source File not exist :" + sourceFile;
System.out.println(" RES :::: " + this.response);
} else {
if (sourceFile != null) {
// open a URL connection to the API
fileInputStream = new FileInputStream(sourceFile);
}
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setConnectTimeout(90000000);
conn.setReadTimeout(90000000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
if (this.filename != null)
conn.setRequestProperty("uploaded_file", this.filename);
dos = new DataOutputStream(conn.getOutputStream());
if (this.filename != null) {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='" + this.filename + "'" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
}
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"customer_id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.customer_id + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"product_name\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.product_name + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"category_id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.category_id + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"expire_time\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.expire_time + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"detail_desc\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.detail_desc + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"esti_ordr_qty\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.esti_ordr_qty + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"esti_ordr_qty_unit\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.esti_ordr_qty_unit + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"filename\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.filename + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
System.out.println("::::::::::::::file name:::::::"+filename);
dos.writeBytes("Content-Disposition: form-data; name=\"image\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(this.image + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
System.out.println(":::::::::::::::;IMAGE:::::::::::"+image);
if (conn.getResponseCode() == 200) {
jobj = null;
is = conn.getInputStream();
b = new byte[is.available()];
is.read(b);
response = new String(b);
Log.print("response : " + response);
}
}
} catch (MalformedURLException ex) {
this.isError = -1;
this.response = "Check api url :" + upLoadServerUri;
Log.print(ex);
Log.error(this.getClass() + "", ex);
} catch (Exception e) {
this.isError = -1;
this.response = "Unable to upload please try again.";
Log.print(e);
Log.error(this.getClass() + "", e);
}
if (dos != null) {
try {
dos.flush();
dos.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
dos = null;
is = null;
conn = null;
jobj = null;
b = null;
buffer = null;
fileInputStream = null;
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
JSONObject jobj = null;
try {
System.out.println(" RES POST :::: " + response);
if (this.isError == 0) {
jobj = new JSONObject(response);
System.out.println(" :::: RESPONSE ::: " + response);
if (jobj.getString("status").equalsIgnoreCase("success")) { // success
responseListener.onResponce(Const.API_BUYING_REQUEST, Const.API_RESULT.SUCCESS, null);
} else { // fail
Utils.showCustomeAlertValidation(context, context.getResources().getString(R.string.api_logic_error), "Error", "OK");
responseListener.onResponce(Const.API_BUYING_REQUEST, Const.API_RESULT.FAIL, jobj.getString("msg"));
}
} else {
Utils.showCustomeAlertValidation(context, context.getResources().getString(R.string.api_logic_error), "Error", "OK");
responseListener.onResponce(Const.API_BUYING_REQUEST, Const.API_RESULT.FAIL, null);
}
} catch (Exception e) {
}
}
}
Activity.java
@Override
public void onClick(View v) {
Intent i;
switch (v.getId()) {
case R.id.tv_pro_cat:
i = new Intent(BuyingreqActivity.this, ProCategoryActivity.class);
startActivityForResult(i, 10);
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
@Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
@Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
System.out.println("::::::::::::::Buton send clicked::::::::::::::::::");
fileName = "User_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "_" + System.currentTimeMillis();
PostReqApi = new ChangeProfilePicAPI(BuyingreqActivity.this, Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, ""), name, id, expTime.getText().toString(), productDesc
.getText().toString(), estOrderQty.getText().toString(), "1", fileName, picturePath, responseListener);
PostReqApi.execute();
break;
case R.id.iv_img:
selectImageFromGallery();
break;
}
}
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
decodeFile(picturePath);
}
if (requestCode == 10) {
if (resultCode == RESULT_OK) {
id = data.getStringExtra("ID");
name = data.getStringExtra("NAME");
System.out.println("::::::::::::::::::On activity result:::::::::::" + id + "==========" + name);
productCategory.setText(name);
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
// encoding....
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, bos);
byte[] data = bos.toByteArray();
encodedFile = Base64.encodeToString(data, Base64.DEFAULT);
proImg.setImageBitmap(bitmap);
}
/*
* CONVERT THE IMAGE TO DATA..!!!
*/
ResponseListener responseListener = new ResponseListener() {
@Override
public void onResponce(String api, API_RESULT result, Object obj) {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (api.equals(Const.API_BUYING_REQUEST)) {
if (result == Const.API_RESULT.SUCCESS) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "Ok");
}
}
}
};