当前位置:首页 » 安卓系统 » 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