android上传数据到服务器
① Android怎么定时上传数据到服务器
首先和服务器建立socket 通讯,接通后进行数据传输,运槐而你仅仅需拦悄游要加简销一个定时器,到规定时间就传输数据,总得来说,你只需要看看socket和定时器这两块内容就完全足够了
② Android怎么定时上传数据到服务器
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity implements Runnable{
/** Called when the activity is first created. */
private Button btn_get = null;
private Button btn_post = null;
private TextView tv_rp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_get = (Button) this.findViewById(R.id.Button01);
btn_post = (Button) this.findViewById(R.id.Button02);
tv_rp = (TextView) this.findViewById(R.id.TextView);
btn_get.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp?par=request-get";
HttpGet request = new HttpGet(httpUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
}else{
tv_rp.setText("请求错误");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btn_post.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
HttpPost request = new HttpPost(httpUrl);
List<namevaluepair> params = new ArrayList<namevaluepair>();
params.add(new BasicNameValuePair("par","request-post"));
try {
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String str = EntityUtils.toString(response.getEntity());
tv_rp.setText(str);
}else{
tv_rp.setText("请求错误");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
new Thread(this).start();
}
public void refresh(){
String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
try {
URL url = new URL(httpUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
InputStream input = urlConn.getInputStream();
InputStreamReader inputreader = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(inputreader);
String str = null;
StringBuffer sb = new StringBuffer();
while((str = reader.readLine())!= null){
sb.append(str).append("\n");
}
if(sb != null){
tv_rp.setText(sb.toString());
}else{
tv_rp.setText("NULL");
}
reader.close();
inputreader.close();
input.close();
reader = null;
inputreader = null;
input = null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Handler handler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
refresh();
}
};
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
③ android中如何上传图片到ftp服务器
在安卓环境下可以使用,在java环境下也可以使用,已经在Java环境下实现了功能,然后移植到了安卓手机上,其它都是一样的。
[java] view plain
package com.photo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FileTool {
/**
* Description: 向FTP服务器上传文件
*
* @param url
* FTP服务器hostname
* @param port
* FTP服务器端口
* @param username
* FTP登录账号
* @param password
* FTP登录密码
* @param path
* FTP服务器保存目录,是linux下的目录形式,如/photo/
* @param filename
* 上传到FTP服务器上的文件名,是自己定义的名字,
* @param input
* 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String url, int port, String username,
String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
// 测试
public static void main(String[] args) {
FileInputStream in = null ;
File dir = new File("G://pathnew");
File files[] = dir.listFiles();
if(dir.isDirectory()) {
for(int i=0;i<files.length;i++) {
try {
in = new FileInputStream(files[i]);
boolean flag = uploadFile("17.8.119.77", 21, "android", "android",
"/photo/", "412424123412341234_20130715120334_" + i + ".jpg", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
以上为java代码,下面是android代码。
[java] view plain
package com.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new uploadThread().start();
}
class uploadThread extends Thread {
@Override
public void run() {
FileInputStream in = null ;
File dir = new File("/mnt/sdcard/DCIM/Camera/test/");
File files[] = dir.listFiles();
if(dir.isDirectory()) {
for(int i=0;i<files.length;i++) {
try {
in = new FileInputStream(files[i]);
boolean flag = FileTool.uploadFile("17.8.119.77", 21, "android", "android",
"/", "412424123412341234_20130715120334_" + i + ".jpg", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
}
④ android怎么传map对象到服务器
Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方式向服务器提交数据的方法。
代码比较简单,这里不去过多的阐述,直接看代码。
/**
* @author Dylan 本类封装了Android中向web服务器提交数据的两种方式四种方法
*/郑岁唯
public class {
**
* 使用get请求以普通方式提交数据
*
* @param map
* 传递进来的数据,以map的形式进行了封装
* @param path
* 要求服务器servlet的地址
* @return 返雀渗回的boolean类型的参数
* @throws Exception
*/
public Boolean submitDataByDoGet(Map<String, String> map, String path)
throws Exception {
// 拼凑出请求地址
StringBuilder sb = new StringBuilder(path);
sb.append("?");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
String str = sb.toString();
System.out.println(str);
URL Url = new URL(str);
HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
HttpConn.setRequestMethod("GET");
HttpConn.setReadTimeout(5000);
// GET方式的请求不用设置什么DoOutPut()之类的吗?
if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return true;
}
return false;
}
/**
* 普通方式的DoPost请求提交数据
*
* @param map
* 传递进来的数据,以map的形式进行了封装
* @param path
* 要求服务器servlet的地喊培址
* @return 返回的boolean类型的参数
* @throws Exception
*/
public Boolean submitDataByDoPost(Map<String, String> map, String path) throws Exception {
// 注意Post地址中是不带参数的,所以newURL的时候要注意不能加上后面的参数
URL Url = new URL(path);
// Post方式提交的时候参数和URL是分开提交的,参数形式是这样子的:name=y&age=6
StringBuilder sb = new StringBuilder();
// sb.append("?");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
String str = sb.toString();[/font][/size]
HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
HttpConn.setRequestMethod("POST");
HttpConn.setReadTimeout(5000);
HttpConn.setDoOutput(true);
HttpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
HttpConn.setRequestProperty("Content-Length",
String.valueOf(str.getBytes().length));
OutputStream os = HttpConn.getOutputStream();
os.write(str.getBytes());
if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return true;
}
return false;
}
/**
* 以HttpClient的DoGet方式向服务器发送请数据
*
* @param map
* 传递进来的数据,以map的形式进行了封装
* @param path
* 要求服务器servlet的地址
* @return 返回的boolean类型的参数
* @throws Exception
*/
public Boolean submitDataByHttpClientDoGet(Map<String, String> map,
String path) throws Exception {
HttpClient hc = new DefaultHttpClient();
// 请求路径
StringBuilder sb = new StringBuilder(path);
sb.append("?");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue());
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
String str = sb.toString();
System.out.println(str);
HttpGet request = new HttpGet(sb.toString());[/font][/size]
HttpResponse response = hc.execute(request);
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return true;
}
return false;
}
复制代码
/**
* 以HttpClient的DoPost方式提交数据到服务器
*
* @param map
* 传递进来的数据,以map的形式进行了封装
* @param path
* 要求服务器servlet的地址
* @return 返回的boolean类型的参数
* @throws Exception
*/
public Boolean submintDataByHttpClientDoPost(Map<String, String> map, String path) throws Exception {
// 1. 获得一个相当于浏览器对象HttpClient,使用这个接口的实现类来创建对象,DefaultHttpClient
HttpClient hc = new DefaultHttpClient();
// DoPost方式请求的时候设置请求,关键是路径
HttpPost request = new HttpPost(path);
// 2. 为请求设置请求参数,也即是将要上传到web服务器上的参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
NameValuePair nameValuePairs = new BasicNameValuePair(
entry.getKey(), entry.getValue());
parameters.add(nameValuePairs);
}
// 请求实体HttpEntity也是一个接口,我们用它的实现类UrlEncodedFormEntity来创建对象,注意后面一个String类型的参数是用来指定编码的
HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
request.setEntity(entity);
// 3. 执行请求
HttpResponse response = hc.execute(request);
// 4. 通过返回码来判断请求成功与否
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return true;
}
return false;
}
}
⑤ Android上大文件传输到服务器,最大能传输多大的文件
Android 上传时, 虽然他的定义是long型的, 但是字节长度还是会受到 Integer.Max的影响,所以上传是多只能传 2.1G 的文件.
⑥ android中数据上传到服务器怎么实现
服务器端写个servlet,然后在doPost()方法里处理客户端上传的文件,大概代码: DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024); // 设置最多只允许在内存中存储的数据, 单位:字节 factory.setRepository(cachepath); // 设置一旦文件大小超过设定值时数据存放的目录 ServletFileUpload srvFileUpload = new ServletFileUpload(factory); srvFileUpload.setSizeMax(1024 * 1024 * 1024); // 设置允许用户上传文件大小, 单位:字节 // 开始读取上传信息 List fileItems = null; try { fileItems = srvFileUpload.parseRequest(request); } catch (Exception e) { System.out.println("获取上传信息。。。。。。失败"); } // 依次处理每个上传的文件 Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 忽略其他不是文件域的所有表单信息 if (!item.isFormField()) { // 取出文件域的所有表单信息 } else { // 取出不是文件域的所有表单信息 } }
⑦ android 如何把一个数据库文件提交到服务器上面去
json就和map的用法一样,new一个JSONObject json=new JSONObject();
json.put("username", username);
json.put("password",password);
用httppclient这个类传过去,post请求的话代码比较多就不写了,我说下get请求比如你的web项目名字是ServletTest,并且你在项目里写个servlet类名字叫test。那么没有绑定域名的情况下url地址应该是http : // +localhost:8080/ ServletTest/test?msg= ( json.toString)。注意括号内要在代码实现。 然后在服务器端收的信息就是{“username”:username , "password": password}格式的数据了。在你的test类里面doGet(HttpRequest request , HttpResponse respone){
String msg=request.getParameter("msg");//就能得到{“username”:username , "passwor。。。。
然后JSONObject serverjson=new JSONObject(msg);
String name= serverjson.getString("username");
String password=serverjson.getString("password");
这样就是封装发送解析的过程
}.
⑧ 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手机向服务器端发送数据,
是在WINDOWS下开发?用系统的IIS吧,在internet 信息服务里添加个网站,设置好路径,然后弄个html文件写死你的模拟数据放在你设定的文件路径下。可以测试就好