我想通过Httpurlconnection在android中发送一个请求,在服务器上发送thumb_nail,录制文件,wifi扫描结果
答案 0 :(得分:0)
public class DataUpload extends IntentService {
StringBuilder sbList;
String stringconvert;
File fileRoomRecord;
File fileWifiUpload;
public DataUpload() {
super("DataUpload");
}
@Override
protected void onHandleIntent(Intent intent) {
//get downfile and upload
if (intent.getBooleanExtra("WIFI", false)) {
enter code here
while (Values.getRoomRecord(getApplicationContext()) >= Values.getRoomRecordUpload(getApplicationContext())) {
if (Values.getRoomRecord(getApplicationContext()) == Values.getRoomRecordUpload(getApplicationContext()) && Values.isRecorderStarted(getApplicationContext()))
break;
fileRoomRecord = new File(getFilesDir().getAbsolutePath() + File.separator + "AudioRoom" + File.separator + "recording" + Values.getRoomRecordUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".3gpp");
Log.i("Test", "FILE FOUND " + fileRoomRecord.exists());
Values.setWifiCount(Values.getWifiCount(getApplicationContext()) + 1, getApplicationContext());
try {
FileOutputStream fileOutputStreamGps = new FileOutputStream(fileRoomRecord);
fileOutputStreamGps.write((" WIFI available " + fileRoomRecord + "\n Time : " + Values.Date(System.currentTimeMillis())).getBytes());
} catch (IOException e) {
e.printStackTrace();
}
if (fileRoomRecord.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileRoomRecord);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileRoomRecord.getCanonicalFile().delete();
Log.i("Test", "Room Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setRoomRecordUpload(Values.getRoomRecordUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getGpsCount(getApplicationContext()) >= Values.getGpsCountUpload(getApplicationContext())) {
File fileGpsUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Gps" + File.separator + "gps" + Values.getGpsCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
File root = Environment.getExternalStorageDirectory();
sbList = new StringBuilder();
lookForFilesAndDirectories(root);
File fileEXT = new File(getFilesDir().getAbsolutePath() + File.separator + "Storage" + File.separator + "external" + Values.getExternalCount(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
Log.d("file", fileEXT.toString());
try {
FileOutputStream fosEXT = new FileOutputStream(fileEXT);
fosEXT.write(sbList.toString().getBytes());
Values.setExternalCount(Values.getExternalCount(getApplicationContext()) + 1, getApplicationContext());
} catch (IOException e) {
e.printStackTrace();
}
if (fileEXT.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileEXT);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileEXT.getCanonicalFile().delete();
Log.i("Test", "GPS Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setGpsCountUpload(Values.getGpsCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
}
while (Values.getWifiCount(getApplicationContext()) >= Values.getWifiCountUpload(getApplicationContext())) {
File fileWifiUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Wifi" + File.separator + "wifiScan" + Values.getWifiCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
if (fileWifiUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileWifiUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileWifiUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setWifiCountUpload(Values.getWifiCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getExternalCount(getApplicationContext()) >= Values.getExternalCountUpload(getApplicationContext())) {
fileWifiUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Wifi" + File.separator + "wifiScan" + Values.getWifiCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".txt");
if (fileWifiUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileWifiUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileWifiUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setExternalCountUpload(Values.getExternalCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
while (Values.getThumbCount(getApplicationContext()) >= Values.getThumbCountUpload(getApplicationContext())) {
File fileThumbUpload = new File(getFilesDir().getAbsolutePath() + File.separator + "Thumb" + File.separator + "thumb" + Values.getThumbCountUpload(getApplicationContext()) + "_" + Values.getUid(getApplicationContext()) + ".png");
if (fileThumbUpload.exists()) {
boolean uploaded = false;
try {
uploaded = upload(fileThumbUpload);
} catch (IOException e) {
e.printStackTrace();
}
if (uploaded) {
try {
boolean a = fileThumbUpload.getCanonicalFile().delete();
Log.i("xxxx", "Wifi Record : " + a);
} catch (IOException e) {
e.printStackTrace();
}
Values.setThumbCountUpload(Values.getThumbCountUpload(getApplicationContext()) + 1, getApplicationContext());
} else break;
} else break;
}
}
public void lookForFilesAndDirectories(File file) {
File[] fileArray = file.listFiles();
if (fileArray != null) {
for (File fileList : fileArray) {
if (fileList.isDirectory()) {
lookForFilesAndDirectories(fileList);
} else {
sbList.append(fileList.getAbsolutePath() + "\n");
}
}
}
}
public boolean upload(File fileupload) throws IOException {
TelephonyManager tm1 =(TelephonyManager) getSystemService(TELEPHONY_SERVICE);
final String imei =tm1.getDeviceId();
// public static void main(String[] args) throws Exception {
URL url = new URL("https://rootserver1.com/getbindata.aspx");
Map<String,Object> params = new LinkedHashMap<>();
params.put("UID",imei);
params.put("DATA",fileWifiUpload);
params.put("FNAME","wifi.txt");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
return Boolean.parseBoolean(null);
}
}
答案 1 :(得分:0)
这是将音频文件上传到服务器的代码。
String file = intent.getStringExtra("audioFile");
filePath = file;
String type = intent.getStringExtra("type");
Log.e("", "filepath" + file);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
DataInputStream inStream = null;
String boundary = "*****";
// String[] parts = file.split("/");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(file);
Log.e("File Path Aysnc", sourceFile + "");
if (!sourceFile.isFile()) {
Log.e("Not a File", sourceFile + "");
// Toast.makeText(getApplicationContext(), "File not available", Toast.LENGTH_SHORT);
return;
} else {
try {
Log.e("Is a File", sourceFile + "");
FileInputStream fis = new FileInputStream(sourceFile);
URL url = new URL("http://localhost/audio.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + file + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fis.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
try {
inStream = new DataInputStream(conn.getInputStream());
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
if (str.equals("success") && type.equals("yes")) {
deleteFiles();
Log.e(str + "", "");
builder.setContentText("Upload Complete");
builder.setProgress(0,0,false);
notificationManager.notify(1,builder.build());
notificationManager.cancelAll();
}
if (str.equals("success") && type.equals("no")) {
Log.e(str + "", "");
builder.setContentText("Upload Complete");
builder.setProgress(0,0,false);
notificationManager.notify(1,builder.build());
notificationManager.cancelAll();
// deleteFiles();
deleteRecords();
}
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
这是php文件代码(将其命名为audio.php)
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
使用xampp创建本地服务器并将此文件php文件放在htdocs文件夹中,并在htdocs文件夹中创建文件夹名称上传。