Java 将图像/文本文件从Android发送到Web服务器(本地主机)
我对Android编程非常陌生,我的任务是向web服务器(localhost)发送图像和文本数据,但是我已经尝试了很多代码来完成这项工作 它们都不起作用。每当我试图执行代码时,我的应用程序就会崩溃,所以我决定调试代码,看看问题出在哪里。然后我发现 每当发现一个多端口时,代码就会崩溃。。我真的不知道为什么 代码是这样的Java 将图像/文本文件从Android发送到Web服务器(本地主机),java,android,Java,Android,我对Android编程非常陌生,我的任务是向web服务器(localhost)发送图像和文本数据,但是我已经尝试了很多代码来完成这项工作 它们都不起作用。每当我试图执行代码时,我的应用程序就会崩溃,所以我决定调试代码,看看问题出在哪里。然后我发现 每当发现一个多端口时,代码就会崩溃。。我真的不知道为什么 代码是这样的 Log.v(TAG, "(1)"); HttpClient httpClient; HttpPost postRequest; Log.v(TAG, "(2)" + picture
Log.v(TAG, "(1)");
HttpClient httpClient;
HttpPost postRequest;
Log.v(TAG, "(2)" + picturePath);
MultipartEntity reqEntity;
ResponseHandler<String> responseHandler;
Log.v(TAG, "(3)");
File file;
FileBody fileBody;
Log.v(TAG, "(4)");
httpClient = new DefaultHttpClient();
postRequest = new HttpPost("http://192.168.5.132/mysite/test.php");
responseHandler = new BasicResponseHandler();
Log.v(TAG, "(5)");
// Indicate that this information comes in parts (text and file)
reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Log.v(TAG, "(6)");
file = new File(picturePath);
fileBody = new FileBody(file, "images/jpeg");
reqEntity.addPart("fileupload", fileBody);
Log.v(TAG, "(7)");
try {
reqEntity.addPart("username", new StringBody("un"));
reqEntity.addPart("password", new StringBody("pw"));
postRequest.setEntity(reqEntity);
httpClient.execute(postRequest, responseHandler);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
真的需要你的帮助。。非常感谢你 设备/仿真器本身是一台拥有自己本地主机循环的机器 正如您所了解的,当您使用emulator时,localhost(127.0.0.1)指的是设备自己的环回服务,而不是您可能期望的机器上的环回服务 因此,每当你给locahost/127.0.0.x,这意味着它试图在你的设备环境中搜索你的服务,所以它会失败。因为您的web服务项目在设备/仿真器循环上不可用 因此,可以使用10.0.2.2访问您的实际计算机,这是一个别名,用于帮助开发 网络地址空间
看看这个 试试这个,它可能会对您有所帮助。它是使用AsyncHttpClient库完成的,获取jar文件并将其附加到您的项目中,然后使用以下代码上载任何文件-
RequestParams params=new RequestParams();
String file = getImagePath().toString();//get path of file you want to upload
File myfile_one=new File(file);
try {
params.put("image1", myfile_one);//image 1 is the key(it uses key-value pair)
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AsyncHttpClient client=new AsyncHttpClient();
client.post(Constant.url_two, params,new AsyncHttpResponseHandler(){
//here implement the methods of library and write rest of your code
}
您可以在链接中找到其他连接到服务器的方法。试试看,这真的很简单。试试这段代码100%正常工作。图像上传是通过多部分数据传递完成的
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fileupload.MainActivity"
tools:ignore="MergeRootFrame" >
<ImageView
android:id="@+id/imageView_pic"
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc_ab_bottom_solid_light_holo" />
<Button
android:id="@+id/button_selectpic"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="@+id/imageView_pic"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="Browse" />
<Button
android:id="@+id/uploadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button_selectpic"
android:layout_alignRight="@+id/button_selectpic"
android:layout_below="@+id/button_selectpic"
android:text="upload" />
<TextView
android:id="@+id/messageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/uploadButton"
android:layout_alignRight="@+id/uploadButton"
android:layout_below="@+id/uploadButton"
android:layout_marginTop="38dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
php服务器代码
<?php
$response = array();
if (empty($_FILES) || $_FILES['file']['error']) {
$response["code"] = 2;
$response["message"] = "failed to move uploaded file";
echo json_encode($response);
}
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploads/$fileName";
// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open input Stream error occurred.";
echo json_encode($response);
@fclose($in);
@fclose($out);
@unlink($_FILES['file']['tmp_name']);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open output error occurred.";
echo json_encode($response);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$response["code"] = 2;
$response["message"] = "successfully uploaded";
echo json_encode($response);
?>
将所需值传递给此函数,并在php上添加$\u post[“username”]、$\u post[“password”]
public JSONObject getJSONFromUrl(String url, String username,
String password, String photo_path) {
InputStream is = null;
JSONObject jObj = null;
static String jsonResp = "";
String CONTENT_TYPE_JSON = "application/json";
static String json = "";
Context context;
try {
File file = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(photo_path != null)
file = new File(photo_path);
//temp end
entity.addPart("username", new StringBody(username));
entity.addPart("password", new StringBody(password));
entity.addPart("file", new FileBody(file));
entity.addPart("filetype",new StringBody("jpeg"));
// entity.addPart("photo", new
// StringBody("/storage/sdcard0/Download/1.jpg"));
httpPost.setEntity(entity);
Log.d("URL Request: ", url.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
您可以使用截取将文件从android上传到服务器 在这里检查
您是否能够从设备或模拟器连接到本地主机,或者是否安装了正确的库?看看你为什么要用它。HttpMultipartMode.BROWSER\u兼容选项?@indra抱歉,回复太晚。。我正在检查我的设备是否可以访问我的本地主机,是。。它可以访问它。。我通过从我的localhost调用一个HTML页面来测试它。它不是localhost:。因此,您指定的特定ip可能是您的系统ip。@lavekush ip地址10.0.x.x不会适用于所有情况。但如果您在cmd提示符中使用ipconfig获取ipv4。Ip看起来像192.x.x.x。我使用了你代码中的UploadFile函数,并将其插入到我的代码中。。但是它仍然崩溃。。这次它在执行
dos=newdataoutputstream(conn.getOutputStream())之前停止代码>。。我还更改了代码中重要变量的值,以便在我的代码上运行..检查getJSONFromUrl函数
<?php
$response = array();
if (empty($_FILES) || $_FILES['file']['error']) {
$response["code"] = 2;
$response["message"] = "failed to move uploaded file";
echo json_encode($response);
}
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploads/$fileName";
// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open input Stream error occurred.";
echo json_encode($response);
@fclose($in);
@fclose($out);
@unlink($_FILES['file']['tmp_name']);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open output error occurred.";
echo json_encode($response);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$response["code"] = 2;
$response["message"] = "successfully uploaded";
echo json_encode($response);
?>
entity.addPart("user_id", new StringBody(user_id));
Log.d("userid",user_id);
entity.addPart("username", new StringBody(username));
entity.addPart("password", new StringBody(password));
entity.addPart("filetype",new StringBody("jpeg"));
// entity.addPart("photo", new
// StringBody("/storage/sdcard0/Download/1.jpg"));
httpPost.setEntity(entity);
Log.d("URL Request: ", url.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
public JSONObject getJSONFromUrl(String url, String username,
String password, String photo_path) {
InputStream is = null;
JSONObject jObj = null;
static String jsonResp = "";
String CONTENT_TYPE_JSON = "application/json";
static String json = "";
Context context;
try {
File file = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(photo_path != null)
file = new File(photo_path);
//temp end
entity.addPart("username", new StringBody(username));
entity.addPart("password", new StringBody(password));
entity.addPart("file", new FileBody(file));
entity.addPart("filetype",new StringBody("jpeg"));
// entity.addPart("photo", new
// StringBody("/storage/sdcard0/Download/1.jpg"));
httpPost.setEntity(entity);
Log.d("URL Request: ", url.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}