Java 图像上传到php服务器的错误响应=httpclient.execute(httppost);
我有两个文件,一个是主要活动,第二个是多方活动 我把这两个文件都发了 MainActivity.javaJava 图像上传到php服务器的错误响应=httpclient.execute(httppost);,java,php,android,http-post,httpclient,Java,Php,Android,Http Post,Httpclient,我有两个文件,一个是主要活动,第二个是多方活动 我把这两个文件都发了 MainActivity.java package com.example.picupload; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStr
package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button mTakePhoto;
private ImageView mImageView;
private static final String TAG = "upload";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.take_photo:
takePhoto();
break;
}
}
private void takePhoto() {
// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// startActivityForResult(intent, 0);
dispatchTakePictureIntent();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i(TAG, "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
setPic();
// Bitmap bitmap = (Bitmap) data.getExtras().get("data");
// if (bitmap != null) {
// mImageView.setImageBitmap(bitmap);
// try {
// sendPhoto(bitmap);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
}
private void sendPhoto(Bitmap bitmap) throws Exception {
new UploadTask().execute(bitmap);
}
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
setProgress(0);
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
/**
* http://developer.android.com/training/camera/photobasics.html
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
mImageView.setImageBitmap(rotatedBMP);
try {
sendPhoto(rotatedBMP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
saveimage.php
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "upload/" . $_FILES['myFile']['name']);
echo 'successful';
}
?>
中的获取错误
试一试{
response=httpclient.execute(httppost);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
请帮我解决 嘿,您可以使用此方法将图像发送到服务器
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public static JSONObject sendJSONDataWithImage() {
String Content = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.8.84:8003/savetofile.php");
File file = new File(yourFilePathwithfileName);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
int size = (int) file.length();
byte[] bytes = new byte[size];
ByteArrayBody bab = null;
try {
BufferedInputStream buf = new BufferedInputStream(
new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
bab = new ByteArrayBody(bytes, yourFilePathwithfileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// reqEntity.addPart("user_id", new StringBody(otherParameter,chars));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
reqEntity.addPart("myFile", bab);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response;
try {
response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
json = s.toString();
System.out.println("Response.............: " + json);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
Log.e("add emp with img Response", "> " + json.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}在你的android系统中试试这个简单的代码,它对我很有用
String url = "";// URL where image has to be uploaded
String fileName = ""; //path of file to be uploaded
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent = new FiSystem.out.println("hello");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
希望这能帮助你解决你的问题 请尝试以下代码:
package com.secondhandbooks.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.secondhandbooks.util.ConvertStreamIntoString;
import com.secondhandbooks.util.SaveImageIntoDrawable;
public abstract class BaseAsync_Post extends AsyncTask<String, String, InputStream>
{
Context context ;
private HttpPost httppost;
String url ;
Dictionary<String, String> dictionary ;
public BaseAsync_Post(String url , Dictionary<String, String> dictionary, Context context) {
this.url = url ;
this.dictionary = dictionary;
this.context = context ;
Enumeration<String> enumeration = dictionary.keys() ;
showLogs("constructor") ;
while ( enumeration.hasMoreElements() )
{
showLogs( enumeration.nextElement() ) ;
}
}
@Override
abstract protected void onPreExecute() ;
@Override
abstract protected void onPostExecute(InputStream result) ;
@Override
protected InputStream doInBackground(String... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(50);
Enumeration<String> enumeration = dictionary.keys() ;
while ( enumeration.hasMoreElements() )
{
String key = enumeration.nextElement() ;
if ( key.equals("file") )
{
final File file = new File(SaveImageIntoDrawable.savedImagePath);
if ( file.isFile() )
{
showLogs("is file");
}
else
{
showLogs("no-file");
}
FileBody fb = new FileBody(file);
entity.addPart(key, fb);
}
else
{
entity.addPart(key, new StringBody(dictionary.get(key)));
}
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1);
is = bufHttpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
showLogs("ClientProtocolException");
} catch (IOException e) {
e.printStackTrace();
showLogs("IOException");
}
return is;
}
public String getString(JSONObject json, String TAG) {
String returnParseData = "";
try {
Object aObj = json.get(TAG);
if (aObj instanceof Boolean) {
returnParseData = Boolean.toString(json.getBoolean(TAG));
} else if (aObj instanceof Integer) {
returnParseData = Integer.toString(json.getInt(TAG));
} else if (aObj instanceof String) {
returnParseData = json.getString(TAG);
} else {
returnParseData = json.getString(TAG);
}
} catch (Exception err) {
err.printStackTrace();
returnParseData = "";
}
return returnParseData;
}
public String getIntintoString(JSONObject json, String TAG) {
int returnParseData = -1;
try {
returnParseData = json.getInt(TAG) ;
} catch (Exception err) {
err.printStackTrace();
returnParseData = -1;
}
return Integer.toString(returnParseData) ;
}
public void showLogs ( String msg )
{
Log.e("HTTP-POST", msg) ;
}
}
package com.secondhandbooks.http;
导入java.io.File;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.ArrayList;
导入java.util.Dictionary;
导入java.util.Enumeration;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.BufferedHttpEntity;
导入org.apache.http.entity.mime.HttpMultipartMode;
导入org.apache.http.entity.mime.MultipartEntity;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.entity.mime.content.StringBody;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONObject;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.util.Log;
导入com.secondhandbooks.util.ConvertStreamIntoString;
导入com.secondhandbooks.util.SaveImageIntoDrawable;
公共抽象类BaseAsync\u Post扩展了AsyncTask
{
语境;
私有HttpPost HttpPost;
字符串url;
字典;
public BaseAsync_Post(字符串url、字典字典、上下文){
this.url=url;
这本字典=字典;
this.context=上下文;
枚举=dictionary.keys();
展示日志(“建造商”);
while(枚举.hasMoreElements())
{
showLogs(enumeration.nextElement());
}
}
@凌驾
抽象受保护的void onPreExecute();
@凌驾
抽象受保护的void onPostExecute(InputStream结果);
@凌驾
受保护的InputStream doInBackground(字符串…参数){
//TODO自动生成的方法存根
//TODO自动生成的方法存根
InputStream=null;
HttpClient HttpClient=新的DefaultHttpClient();
httppost=新的httppost(url);
MultipartEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
尝试
{
List nameValuePairs=新的ArrayList(50);
枚举=dictionary.keys();
while(枚举.hasMoreElements())
{
String key=enumeration.nextElement();
if(key.equals(“文件”))
{
最终文件=新文件(SaveImageIntoDrawable.savedImagePath);
if(file.isFile())
{
显示日志(“is文件”);
}
其他的
{
显示日志(“无文件”);
}
FileBody fb=新的FileBody(文件);
实体。添加部分(键,fb);
}
其他的
{
addPart(key,newstringbody(dictionary.get(key));
}
}
httppost.setEntity(实体);
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity1=response.getEntity();
BufferedHttpEntity bufHttpEntity=新的BufferedHttpEntity(entity1);
is=bufhttpenty.getContent();
}捕获(客户端协议例外e){
e、 printStackTrace();
显示日志(“客户端协议例外”);
}捕获(IOE异常){
e、 printStackTrace();
显示日志(“IOException”);
}
回报是;
}
公共字符串getString(JSONObject json,字符串标记){
字符串returnParseData=“”;
试一试{
对象aObj=json.get(标记);
if(aObj instanceof Boolean){
returnParseData=Boolean.toString(json.getBoolean(TAG));
}else if(aObj instanceof Integer){
returnParseData=Integer.toString(json.getInt(TAG));
}else if(字符串的aObj实例){
returnParseData=json.getString(标记);
}否则{
returnParseData=json.getString(标记);
}
}捕获(异常错误){
err.printStackTrace();
returnParseData=“”;
}
返回数据;
}
公共字符串getIntontoString(JSONObject json,字符串标记){
int returnParseData=-1;
试一试{
returnParseData=json.getInt(标记);
}捕获(异常错误){
err.printStackTrace();
returnParseData=-1;
}
返回整数.toString(returnParseData);
}
公共void显示日志(字符串msg)
{
Log.e(“HTTP-POST”,msg);
}
}
为我工作,请尝试使用不同的网络,如wifi或移动数据
//进行服务器呼叫
HttpResponse response=httpclient.execute(httppost);
HttpEntity r_entity=response.getEntity()
它将是get direct异常,不会响应任何内容。好的,您可以调试它并在ClientProtocolException中查看e的值吗?是的,我已经调试好了。它来了。超过2或3分钟后
package com.secondhandbooks.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.secondhandbooks.util.ConvertStreamIntoString;
import com.secondhandbooks.util.SaveImageIntoDrawable;
public abstract class BaseAsync_Post extends AsyncTask<String, String, InputStream>
{
Context context ;
private HttpPost httppost;
String url ;
Dictionary<String, String> dictionary ;
public BaseAsync_Post(String url , Dictionary<String, String> dictionary, Context context) {
this.url = url ;
this.dictionary = dictionary;
this.context = context ;
Enumeration<String> enumeration = dictionary.keys() ;
showLogs("constructor") ;
while ( enumeration.hasMoreElements() )
{
showLogs( enumeration.nextElement() ) ;
}
}
@Override
abstract protected void onPreExecute() ;
@Override
abstract protected void onPostExecute(InputStream result) ;
@Override
protected InputStream doInBackground(String... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(50);
Enumeration<String> enumeration = dictionary.keys() ;
while ( enumeration.hasMoreElements() )
{
String key = enumeration.nextElement() ;
if ( key.equals("file") )
{
final File file = new File(SaveImageIntoDrawable.savedImagePath);
if ( file.isFile() )
{
showLogs("is file");
}
else
{
showLogs("no-file");
}
FileBody fb = new FileBody(file);
entity.addPart(key, fb);
}
else
{
entity.addPart(key, new StringBody(dictionary.get(key)));
}
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1);
is = bufHttpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
showLogs("ClientProtocolException");
} catch (IOException e) {
e.printStackTrace();
showLogs("IOException");
}
return is;
}
public String getString(JSONObject json, String TAG) {
String returnParseData = "";
try {
Object aObj = json.get(TAG);
if (aObj instanceof Boolean) {
returnParseData = Boolean.toString(json.getBoolean(TAG));
} else if (aObj instanceof Integer) {
returnParseData = Integer.toString(json.getInt(TAG));
} else if (aObj instanceof String) {
returnParseData = json.getString(TAG);
} else {
returnParseData = json.getString(TAG);
}
} catch (Exception err) {
err.printStackTrace();
returnParseData = "";
}
return returnParseData;
}
public String getIntintoString(JSONObject json, String TAG) {
int returnParseData = -1;
try {
returnParseData = json.getInt(TAG) ;
} catch (Exception err) {
err.printStackTrace();
returnParseData = -1;
}
return Integer.toString(returnParseData) ;
}
public void showLogs ( String msg )
{
Log.e("HTTP-POST", msg) ;
}
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
} } catch (ClientProtocolException e) {
responseString = e.toString(); } catch (IOException e) {
responseString = e.toString(); } return responseString;