手机拍照与上传图片是APP中很常用的功能。
我们先写个布局,然后代码实现。
MediaStore.ACTION_IMAGE_CAPTURE); //调用相机
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" >
<include android:id="@+id/title" layout="@layout/title" />
</RelativeLayout>
<LinearLayout style="@style/common_linearlayout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical" >
<ImageView android:id="@+id/load_ic" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="280dp" android:scaleType="fitCenter" android:src="@drawable/takephoto" />
<FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:paddingBottom="17dp" android:paddingTop="16dp" android:visibility="gone" >
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="示意图" android:textColor="#fa5655" android:textSize="24sp" android:visibility="gone" />
</RelativeLayout>
</FrameLayout>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="25dp" android:layout_marginLeft="15dp" android:layout_marginTop="10dp" android:text="" android:textSize="13sp" />
<Button android:id="@+id/upload" style="@style/common_button_red" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="上传照片" />
</LinearLayout>
2,拍照
//拍完照后,照片要保存的路径。
String tempImg = Environment.getExternalStorageDirectory() + "/appName/"+ "temp.jpg";
private void findView() {
context = this;
mUpload = (Button) findViewById(R.id.upload);
mloadiv = (ImageView) findViewById(R.id.load_ic);
//picName 是个照片文件路径,判断这个 mloadiv 这个位置有没有照片,有的话,直接设置到这。
if (Util.isEmpty(picName) || picName.equals("")) {
} else {
Bitmap bitmap5 = BitmapUtil.getSmallBitmap(picName, true);
mloadiv.setImageDrawable(new BitmapDrawable(getResources(), bitmap5));
}
// 点击按钮出现dialog,选择(拍照,从相册选,取消)
mUpload.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (uptimes >= 8) {
MyToast.showToast(context, "您上传次数过多");
return;
}
if (dialog == null) {
dialog = new AlertDialog.Builder(context).setItems(
new String[]{"拍照", "从手机相册选择", "取消"},
//Dialog 中的监听器
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
if (which == 0) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(
MediaStore.EXTRA_VIDEO_QUALITY,
1);
File out = new File(tempImg);
Uri uri = Uri.fromFile(out);
// 获取拍照后未压缩的原图片,并保存在uri路径中
intent.putExtra(
MediaStore.EXTRA_OUTPUT, uri);
// intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION,
// 180);
startActivityForResult(intent,
Config.requestCode_1);
} else if (which == 1) {
Intent local = new Intent(Intent.ACTION_PICK, null);
local.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(local,
Config.requestCode_4);
} else if (which == 2) {
dialog.dismiss();
}
}
}).create();
}
if (!dialog.isShowing()) {
dialog.show();
}
}
});
}
3,处理图片
/** * 拍照或选择照片 */
@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Config.requestCode_1) {// 拍照
if (resultCode == RESULT_OK) {
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
Bitmap bitmap1 = BitmapUtil.getSmallBitmap(tempImg, true);// getBitmapFromUrl(tempImg,
bitmap1 = BitmapUtil.ImageCompressL2(bitmap1);
if (bitmap1 == null || !saveScalePhoto(bitmap1)) {
MyToast.showToast(this, "获取图片失败,请重试");
return;
}
fileName1 = allurl;
//将照片设置到上图的照片iamageView 中
mloadiv.setImageDrawable(new BitmapDrawable(getResources(),
bitmap1));
PicsUpload();// 开始图片上传
}
}
if (requestCode == Config.requestCode_4&&data!=null) {
Uri uri = data.getData();
if (null != uri) {
String StringUri = uri.toString();
Cursor cursor = null;
int columnIndex = -1;
//如果uri有百分号,将百分号转化为斜线,再进行进一步处理。
if (StringUri.contains("%")) {
try {
StringUri = URLDecoder.decode(StringUri, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
//以file开头的uri,直接截取获取路径
if (StringUri.startsWith("file")) {
fileName = StringUri.substring(StringUri.indexOf("://") + 4);
}
//不以file开头的,即使以content开头的,uri处理。
else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
// 4.4及以上
String[] column = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(uri, column, null, null, null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
fileName = cursor.getString(columnIndex);
}
} else {
// 4.4以下,即4.4以上获取路径的方法
String[] projection = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(uri,
projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
fileName = cursor.getString(column_index);
}
if (fileName != null && !fileName.equals("")) {
String name = Util.getTransTime() + ".jpg";
String fileDir = Environment.getExternalStorageDirectory()
+ "/appName/";
File file = new File(fileDir);
if (!file.exists()) {
file.mkdirs();
}
String picpath = fileDir + name;
// 压缩图片
FileOutputStream out = null;
try {
Bitmap image = BitmapUtil.getSmallBitmap(fileName, true);
if (image == null) {
image = BitmapUtil.getSmallBitmap(fileName, 300, 400, true);
}
//图片缩放
image = BitmapUtil.ImageCompressL(image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (image != null && !image.isRecycled()) {
image.recycle();
image = null;
System.gc();
}
ByteArrayInputStream isBm = new ByteArrayInputStream(
baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中}
baos.close();
Bitmap bitmap = BitmapFactory
.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
out = new FileOutputStream(picpath);// 压缩完存到此路径下面
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);// 把ByteArrayInputStream数据生成图片
// 将输入流复制到输出流中
isBm.close();
// 传给上一页图片路径
fileName1 = picpath;
mloadiv.setImageDrawable(new BitmapDrawable(getResources(),
bitmap));
PicsUpload();// 图片上传完成后提交申请
} catch (FileNotFoundException e) {
e.printStackTrace();
fileName = "";
MyToast.showToast(context, "获取图片失败,请重试");
return;
} catch (IOException e) {
e.printStackTrace();
fileName = "";
MyToast.showToast(context, "获取图片失败,请重试");
return;
} catch (Exception e) {
e.printStackTrace();
fileName = "";
MyToast.showToast(context, "获取图片失败,请重试");
return;
} catch (OutOfMemoryError err) {
fileName = "";
MyToast.showToast(context, "获取图片失败,请重试");
return;
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {//暂时解决没有sd卡选择图片崩溃的问题
// TODO: handle exception
e.printStackTrace();
}
}
} else {
// MyToast.showToast(context, "请选择图片");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
4,上传图片
/** * 上传图片 */
private void PicsUpload() {
mDialog.show();
//开启线程上传照片
new Thread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
try {
dialog.dismiss();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
if (fileName1 != null) {
// int imgid = DownAndUploadPic.uploadImage(flag,fileName1,
// mLoginEntity.getSessionId());
int imgid = DownAndUploadPic.uploadImage(fileName1);
attachmentId = imgid + "";
if (Config.isUpPicTo9999) {
//上傳到9999网站
//返回图片id
attachmentId9999 = DownAndUploadPicTo9999.uploadImage(fileName1);
Logout.e("YCW", "attachmentId=" + attachmentId + "\nattachmentId9999=" + attachmentId9999);
if (imgid != 0 && !"".equals(attachmentId9999)) {
Message message = handler.obtainMessage(0);
message.sendToTarget();
} else {
imgid = 100;
Message message = handler.obtainMessage(1);
message.sendToTarget();
}
} else {
////上傳到另一个网站
Logout.e("YCW", "attachmentId=" + attachmentId);
if (imgid != 0) {
Message message = handler.obtainMessage(0);
message.sendToTarget();
} else {
imgid = 100;
Message message = handler.obtainMessage(1);
message.sendToTarget();
}
}
}
}
}
}).start();
}
5 上传成功或者失败之后怎么办
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(mDialog.isShowing()){
mDialog.dismiss();
}
super.handleMessage(msg);
switch (msg.what) {
case 0:
MyToast.showToast(context, "上传成功");
uptimes++;
Intent intentPic = new Intent();
intentPic.putExtra("picUrl", fileName1);
intentPic.putExtra("attachmentId", attachmentId);
intentPic.putExtra("attachmentId9999", attachmentId9999);
setResult(RESULT_OK, intentPic);
finish();
break;
case 1:
MyToast.showToast(context, "上传失败");
break;
}
}
};
7 存储缩放的图片
/** * 存储缩放的图片 * * @param bitmap 图片数据 */
private boolean saveScalePhoto(Bitmap bitmap) {
// 照片全路径
String fileName = "";
// 文件夹路径
String pathUrl = Environment.getExternalStorageDirectory() + "/appName/";
String imageName = Util.getTransTime() + ".jpg";
FileOutputStream fos = null;
File file = new File(pathUrl);
file.mkdirs();// 创建文件夹
fileName = pathUrl + imageName;
try {
fos = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
allurl = fileName;
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError err) {
} finally {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
8 Bitmap工具类
public class BitmapUtil {
public static Bitmap getSmallBitmap(String filePath, boolean isNeedRotate) {
return getSmallBitmap(filePath, 768, 1024, isNeedRotate);
}
public static Bitmap getSmallBitmap(String filePath, int width, int height,
boolean isNeedRotate) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeFile(filePath, options);
} catch (Exception e1) {
e1.printStackTrace();
return null;
} catch (OutOfMemoryError ex) {
try {
options.inSampleSize = options.inSampleSize * 2;
bitmap = BitmapFactory.decodeFile(filePath, options);
} catch (Exception e1) {
e1.printStackTrace();
return null;
} catch (OutOfMemoryError ex1) {
}
}
if (isNeedRotate) {
int rotate = 0;
try {
ExifInterface mExifInterface = new ExifInterface(filePath);
int result = mExifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (result) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (OutOfMemoryError ex) {
}
if (rotate != 0 && bitmap != null) {
Matrix m = new Matrix();
m.setRotate(rotate, (float) bitmap.getWidth() / 2,
(float) bitmap.getHeight() / 2);
try {
Bitmap tempBmp = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), m, true);
// bmp.recycle();
bitmap = tempBmp;
} catch (OutOfMemoryError ex) {
}
}
}
return bitmap;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
System.gc();
}
return output;
}
//图片缩放位64k
public static Bitmap ImageCompressL(Bitmap bitmap) {
double targetwidth = Math.sqrt(64.00 * 1000);
if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
/ bitmap.getHeight());
// 缩放图片动作
matrix.postScale((float) x, (float) x);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
return bitmap;
}
//图片缩放位100k
public static Bitmap ImageCompressL2(Bitmap bitmap) {
double targetwidth = Math.sqrt(900.00 * 1000);
if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
/ bitmap.getHeight());
// 缩放图片动作
matrix.postScale((float) x, (float) x);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
return bitmap;
}
}
9 图片上传下载的工具类 (1)
public class DownAndUploadPic {
/** * 模拟表单上传图片 * * @param filePath * 图片本地地址 * @return */
public static int uploadImage(String filePath) {
int attachmentId = 0;
HttpURLConnection conn = null;
OutputStream out = null;
DataInputStream in = null;
Reader inputReader = null;// 结果流
BufferedReader reader = null;
URL url = null;
String BOUNDARY = "---------------------------123456789987456321"; // request头和上传文件内容的分隔符
try {
url= new URL(getUpAndDownloadImageUrl()+"upload.do");
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
out = new DataOutputStream(conn.getOutputStream());
if (filePath != null) {
File file = new File(filePath);
String filename = file.getName();
String contentType = "application/octet-stream";
if (filename.endsWith(".jpg")) {
contentType = "image/jpeg";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ "file" + "\"; filename=\"" + filename + "\"\r\n");// file参数名(与后台对应)
// filename:文件名称
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");// "image/jpeg"
// Log.e("YCW", "File =" + strBuf);
System.out.println("File =" + strBuf);
out.write(strBuf.toString().getBytes());
in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
// out.flush();
}
if (Constants.downupPicWithSession) {// 有session的上传
byte[] endData = ("\r\n--" + BOUNDARY + "\r\n").getBytes();
out.write(endData);
StringBuffer strBuf_se = new StringBuffer();
strBuf_se.append("--").append(BOUNDARY).append("\r\n");
strBuf_se
.append("Content-Disposition: form-data; name=\""
+ "sessionId" + "\"\r\n\r\n"
+ Constants.sessionId + "");// session
strBuf_se.append("\r\n--" + BOUNDARY + "--\r\n");
Log.e("AAA", "sessionId =" + strBuf_se.toString());
out.write(strBuf_se.toString().getBytes());
Log.e("AAA", "out =" + out.toString());
} else {
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
}
out.flush();
// out.close();
StringBuffer strBuf = new StringBuffer();
inputReader = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(inputReader);
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line);// .append("\n")
System.out.println("strBuf===" + strBuf);
}
String res = strBuf.toString();
try {
attachmentId = Integer.parseInt(res);
} catch (Exception e) {
Logout.e("AAA", "parse int Failure " + e.getMessage());
attachmentId = 0;
}
reader.close();
reader = null;
} catch (Exception e) {
Logout.e("AAA", "parse int Failure " + e.getMessage());
attachmentId = 0;
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
if (inputReader != null) {
inputReader.close();
inputReader = null;
}
if (reader != null) {
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return attachmentId;
}
}
9,图片上传下载工具类(2)
/** * * 图片上传下载工具类 * 上传图片至9999网站 * * */
public class DownAndUploadPicTo9999 {
/** * 模拟表单上传图片 * * @param filePath * 图片本地地址 * @return */
public static String uploadImage(String filePath) {
int attachmentId = 0;
String attachmentIdStr = "";
HttpURLConnection conn = null;
// OutputStream out = null;
PrintWriter out = null;
DataInputStream in = null;
Reader inputReader = null;// 结果流
BufferedReader reader = null;
URL url = null;
String BOUNDARY = "---------------------------1234567899988745"; // request头和上传文件内容的分隔符
try {
int proid = ActivitySwitch.getInstance().dbProCode;
String proid_str = Integer.toString(proid);
String serviceIP = "";
String servicePort = "";
if (Config.formal_environment){
//9999正式环境
serviceIP = "**.**.**.**";
servicePort = "8014";
}else {
//9999测试环境
serviceIP = "**.**.**.**";
servicePort = "8015";
}
url = new URL("http://"+serviceIP+":"+servicePort+"/CSUPS/9999/apps/appFileUpload");
Logout.e("AAA",url.getAuthority()+url.getPath());
String codeId = ActivitySwitch.company.getCodeId();
/**对部分内容ca加密**/
String req = ""+""+codeId+"13"+"9999";
StringBuffer encryptResult=new StringBuffer(CAHelper.getInstance().loginEncrypt(MyApplication.getInstance(), req));
String encryStr=encryptResult.subSequence(0, encryptResult.lastIndexOf("|")+1).toString();
encryStr = "09999"+URLEncoder.encode(encryStr,"utf-8");
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
//imgFile 图片的二进制
//http://www.cnblogs.com/mailingfeng/archive/2012/01/09/2317100.html
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
for (int len = inputStream.read(temp); len !=-1; len=inputStream.read(temp)) {
outputStream.write(temp,0,len);
}
try {
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
String _64PicData = "";
_64PicData = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
_64PicData = URLEncoder.encode(_64PicData,"utf-8");
StringBuffer buffer = new StringBuffer();
out = new PrintWriter(conn.getOutputStream());
String target = "11102";
String srvMode = "13";
String fileType = ".jpg";
String sign = "加密串";
String imgFile = "加密串"+
"加密串";
String param = 入参;
buffer.append(param);
out.print(buffer.toString());
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
Logout.e("AAA", "连接网络");
inputReader = new InputStreamReader(conn.getInputStream());
Logout.e("AAA", "连接网络完毕");
reader = new BufferedReader(inputReader);
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line);// .append("\n")
System.out.println("strBuf===" + strBuf);
}
Logout.e("AAA", "写数据完毕");
String res = strBuf.toString();
Logout.e("AAA", "网站返回的数据:"+res);
try {
if (res!=null&&!res.equals("")) {
res = res.replace("\\", "");
if (res.startsWith("\"")) {
res = res.substring(1);
}
if (res.endsWith("\"")) {
res = res.substring(0,res.length()-1);
}
Logout.e("AAA", "处理后的数据:"+res);
JSONTokener toker = new JSONTokener(res);
JSONObject object = (JSONObject) toker.nextValue();
String picId = object.getString("webPhotoId");
// attachmentId = Integer.parseInt(picId);
attachmentIdStr = picId;
}else {
attachmentId = 0;
attachmentIdStr = "";
}
} catch (Exception e) {
Log.e("msg", "parse int Failure " + e.getMessage());
attachmentId = 0;
attachmentIdStr = "";
}
reader.close();
reader = null;
} catch (Exception e) {
Log.e("msg", " " + e.getMessage());
attachmentId = 0;
attachmentIdStr = "";
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
if (inputReader != null) {
inputReader.close();
inputReader = null;
}
if (reader != null) {
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return attachmentIdStr;
}