當前位置:首頁 » 安卓系統 » android上傳伺服器

android上傳伺服器

發布時間: 2023-07-30 23:27:41

⑴ Android怎麼定時上傳數據到伺服器

首先和伺服器建立socket 通訊,接通後進行數據傳輸,運槐而你僅僅需攔悄游要加簡銷一個定時器,到規定時間就傳輸數據,總得來說,你只需要看看socket和定時器這兩塊內容就完全足夠了

⑵ Android用post方式上傳到伺服器的問題

在HTTP通信中使用最多的就是GET和POST了,GET請求可以獲取靜態頁面,也可以把參數放在URL字元串的後面,傳遞給伺服器。POST與GET的不同之處在於POST的參數不是放在URL字元串裡面,而是放在HTTP請求數據中。

android 用post方式上傳圖片到伺服器的示例代碼如下:

java">/**
*上傳文件到伺服器類
*/
publicclassUploadUtil{
privatestaticfinalStringTAG="uploadFile";


privatestaticfinalintTIME_OUT=10*1000;//超時時間


="utf-8";//設置編碼


/**
*Android上傳文件到服務端
*
*@paramfile需要上傳的文件
*@paramRequestURL請求的rul
*@return返回響應的內容
*/
publicstaticStringuploadFile(Filefile,StringRequestURL){
Stringresult=null;
StringBOUNDARY=UUID.randomUUID().toString();//邊界標識隨機生成
StringPREFIX="--",LINE_END=" ";
StringCONTENT_TYPE="multipart/form-data";//內容類型


try{
URLurl=newURL(RequestURL);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);//允許輸入流
conn.setDoOutput(true);//允許輸出流
conn.setUseCaches(false);//不允許使用緩存
conn.setRequestMethod("POST");//請求方式
conn.setRequestProperty("Charset",CHARSET);//設置編碼
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("Content-Type",CONTENT_TYPE+";boundary="+BOUNDARY);


if(file!=null){
/**
*當文件不為空,把文件包裝並且上傳
*/
DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
StringBuffersb=newStringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
*這里重點注意:name裡面的值為服務端需要key只有這個key才可以得到對應的文件
*filename是文件的名字,包含後綴名的比如:abc.png
*/


sb.append("Content-Disposition:form-data;name="uploadfile";filename=""
+file.getName()+"""+LINE_END);
sb.append("Content-Type:application/octet-stream;charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStreamis=newFileInputStream(file);
byte[]bytes=newbyte[1024];
intlen=0;
while((len=is.read(bytes))!=-1){
dos.write(bytes,0,len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[]end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
*獲取響應碼200=成功當響應成功,獲取響應的流
*/
intres=conn.getResponseCode();
Log.e(TAG,"responsecode:"+res);
//if(res==200)
//{
Log.e(TAG,"requestsuccess");
InputStreaminput=conn.getInputStream();
StringBuffersb1=newStringBuffer();
intss;
while((ss=input.read())!=-1){
sb1.append((char)ss);
}
result=sb1.toString();
Log.e(TAG,"result:"+result);
//}
//else{
//Log.e(TAG,"requesterror");
//}
}
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnresult;
}


/**
*通過拼接的方式構造請求內容,實現參數傳輸以及文件傳輸
*
*@paramurlServicenetaddress
*@paramparamstextcontent
*@paramfilespictures
*@
*@throwsIOException
*/
publicstaticStringpost(Stringurl,Map<String,String>params,Map<String,File>files)
throwsIOException{
StringBOUNDARY=java.util.UUID.randomUUID().toString();
StringPREFIX="--",LINEND=" ";
StringMULTIPART_FROM_DATA="multipart/form-data";
StringCHARSET="UTF-8";


URLuri=newURL(url);
HttpURLConnectionconn=(HttpURLConnection)uri.openConnection();
conn.setReadTimeout(10*1000);//緩存的最長時間
conn.setDoInput(true);//允許輸入
conn.setDoOutput(true);//允許輸出
conn.setUseCaches(false);//不允許使用緩存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("Charsert","UTF-8");
conn.setRequestProperty("Content-Type",MULTIPART_FROM_DATA+";boundary="+BOUNDARY);


//首先組拼文本類型的參數
StringBuildersb=newStringBuilder();
for(Map.Entry<String,String>entry:params.entrySet()){
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition:form-data;name=""+entry.getKey()+"""+LINEND);
sb.append("Content-Type:text/plain;charset="+CHARSET+LINEND);
sb.append("Content-Transfer-Encoding:8bit"+LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}


DataOutputStreamoutStream=newDataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
//發送文件數據
if(files!=null)
for(Map.Entry<String,File>file:files.entrySet()){
StringBuildersb1=newStringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition:form-data;name="uploadfile";filename=""
+file.getValue().getName()+"""+LINEND);
sb1.append("Content-Type:application/octet-stream;charset="+CHARSET+LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());


InputStreamis=newFileInputStream(file.getValue());
byte[]buffer=newbyte[1024];
intlen=0;
while((len=is.read(buffer))!=-1){
outStream.write(buffer,0,len);
}


is.close();
outStream.write(LINEND.getBytes());
}


//請求結束標志
byte[]end_data=(PREFIX+BOUNDARY+PREFIX+LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
//得到響應碼
intres=conn.getResponseCode();
InputStreamin=conn.getInputStream();
StringBuildersb2=newStringBuilder();
if(res==200){
intch;
while((ch=in.read())!=-1){
sb2.append((char)ch);
}
}
outStream.close();
conn.disconnect();
returnsb2.toString();
}


}

⑶ android 怎麼上傳數組到伺服器

1.使用JSONObject 、JSONArray將一個數組編寫成json格式傳遞到php伺服器中,php程序接受json格式的參數並解析成數組
這個方法可以就是讓php伺服器端解析android上傳的json格式參數,再構建成一個數組,所以不解釋。

2.用拼接欄位,手動遍歷創建所需要發送的key和value,key和value類型為string[],
例如
php端程序需要接受的數組格式為
array=>[ "key1" => "value1",
"key2" => "value2",
"key3" => "value3",
......]
android端的處理為:
string [] key = {"array[key1]","array[key2]","array[key3]",....}
對應的值:
string [] value = {"value1","value2","value3",....}

若php端程序需要接受的數組格式為
array["key1"=>["key11"=>"value11",

⑷ 使用android上傳圖片到伺服器,並且把圖片保存到伺服器的某個文件夾

有兩種方法,第一,把你的圖片轉成位元組流,然後用post方法把位元組流傳到服務端,然後服務端接收到位元組流之後,開啟一個線程把它重新壓縮成圖片,保存在某個文件夾下面。
第二,開啟一個線程,用socket直接把圖片放到stream中傳到服務端,服務端接收後保存到文件夾下。

⑸ android中ftp如何上傳到伺服器最快

這個有幾個不同情況:手機安裝ftp客戶端,AndFTP是android設備上的一款FTP/SFTP/FTPS客戶端軟體,可以實現和電腦一樣的文件傳輸方式,直接連接你的空間即可傳輸。手機沒有客戶端軟體,可以採用中間方式,使用網頁傳輸,叫做webftp工具,就是利用網頁數據傳輸的方式,打開webftp網站,輸入空間的FTP信息連接即可傳輸文件。注意一點,使用webftp需要在空間後台先設置允許連接的IP地址,使空間伺服器允許webftp連接並向其傳輸文件。

⑹ Android 上傳圖片到伺服器

final Map<String, String> params = new HashMap<String, String>();
params.put("send_userId", String.valueOf(id));
params.put("send_email", address);
params.put("send_name", name);
params.put("receive_email", emails);

final Map<String, File> files = new HashMap<String, File>();
files.put("uploadfile", file);

final String request = UploadUtil.post(requestURL, params, files);

⑺ android怎樣上傳圖片到伺服器

界面很簡單,點擊 【選擇圖片】,從圖庫里選擇圖片,顯示到下面的imageview里,點擊上傳,就會上傳到指定的伺服器

布局文件:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="選擇圖片"
android:id="@+id/selectImage"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="上傳圖片"
android:id="@+id/uploadImage"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
/>
</LinearLayout>

Upload Activity:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

public class Upload extends Activity implements OnClickListener {
private static String requestURL = "http://192.168.1.212:8011/pd/upload/fileUpload.do";
private Button selectImage, uploadImage;
private ImageView imageView;

private String picPath = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);

selectImage = (Button) this.findViewById(R.id.selectImage);
uploadImage = (Button) this.findViewById(R.id.uploadImage);
selectImage.setOnClickListener(this);
uploadImage.setOnClickListener(this);

imageView = (ImageView) this.findViewById(R.id.imageView);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectImage:
/***
* 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
*/
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
break;
case R.id.uploadImage:
if (picPath == null) {

Toast.makeText(Upload.this, "請選擇圖片!", 1000).show();
} else {
final File file = new File(picPath);

if (file != null) {
String request = UploadUtil.uploadFile(file, requestURL);
uploadImage.setText(request);
}
}
break;
default:
break;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
/**
* 當選擇的圖片不為空的話,在獲取到圖片的途徑
*/
Uri uri = data.getData();
Log.e(TAG, "uri = " + uri);
try {
String[] pojo = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
ContentResolver cr = this.getContentResolver();
int colunm_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
/***
* 這里加這樣一個判斷主要是為了第三方的軟體選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片了,
* 這樣的話,我們判斷文件的後綴名 如果是圖片格式的話,那麼才可以
*/
if (path.endsWith("jpg") || path.endsWith("png")) {
picPath = path;
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
imageView.setImageBitmap(bitmap);
} else {
alert();
}
} else {
alert();
}

} catch (Exception e) {
}
}

super.onActivityResult(requestCode, resultCode, data);
}

private void alert() {
Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
.setMessage("您選擇的不是有效的圖片")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
picPath = null;
}
}).create();
dialog.show();
}

}

這個才是重點 UploadUtil:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超時時間
private static final String CHARSET = "utf-8"; // 設置編碼
/**
* 上傳文件到伺服器
* @param file 需要上傳的文件
* @param RequestURL 請求的rul
* @return 返回響應的內容
*/
public static int uploadFile(File file, String RequestURL) {
int res=0;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識 隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型

try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流
conn.setDoOutput(true); // 允許輸出流
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST"); // 請求方式
conn.setRequestProperty("Charset", CHARSET); // 設置編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);

if (file != null) {
/**
* 當文件不為空時執行上傳
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這里重點注意: name裡面的值為伺服器端需要key 只有這個key 才可以得到對應的文件
* filename是文件的名字,包含後綴名
*/

sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 獲取響應碼 200=成功 當響應成功,獲取響應的流
*/
res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
} else {
Log.e(TAG, "request error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}

⑻ android怎樣實時上傳崩潰日誌到伺服器

讓系統處理崩潰,然後把錯誤日誌上傳到伺服器並且服務只能運行2秒鍾,如果2秒鍾錯誤日誌沒有上傳到伺服器,那麼這個錯誤信息就不要了。然後再停止服務,在服務銷毀的時候同時銷毀進程。

核心代碼:

public int onStartCommand(Intent intent, int flags, int startId) { stopDelayed = intent.getLongExtra("Delayed", 2000); PackageName = intent.getStringExtra("PackageName"); expection = intent.getStringExtra("exception"); try { //這里上傳崩潰日誌 } catch (java.lang.Exception e) { e.printStackTrace(); } handler.postDelayed(new Runnable() { @Override public void run() {/* Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(PackageName); startActivity(LaunchIntent);*/ KillSelfService.this.stopSelf(); //android.os.Process.killProcess(android.os.Process.myPid()); } }, stopDelayed); return super.onStartCommand(intent, flags, startId);}
@Overridepublic void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy: "); android.os.Process.killProcess(android.os.Process.myPid());}


熱點內容
c語言編程圖書 發布:2025-02-04 19:01:52 瀏覽:894
在哪裡開啟密碼顯示 發布:2025-02-04 18:38:30 瀏覽:787
怎麼查詢qq密碼 發布:2025-02-04 18:20:10 瀏覽:513
python編寫介面 發布:2025-02-04 18:08:30 瀏覽:78
怎麼給游戲設置密碼 發布:2025-02-04 18:03:08 瀏覽:926
商品存儲規劃 發布:2025-02-04 17:45:24 瀏覽:567
ios訪問共享 發布:2025-02-04 17:36:33 瀏覽:335
javabuild 發布:2025-02-04 17:30:19 瀏覽:592
gnulinux編譯 發布:2025-02-04 17:30:18 瀏覽:132
蘇州阿里雲伺服器專網 發布:2025-02-04 17:21:05 瀏覽:526