android通过http上传文件到web服务器端
代码如下 | 复制代码 |
<?php ///如果有上传文件则接收 if($_FILES){ $target_path = $target_path . basename( $_FILES['file1']['name']); try{ if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['file1']['name']). " has been uploaded"; } } catch( Exception $e ) { echo $e->getMessage(); } } ?> Android 代码: package com.nbcio.baishicha.test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast;
/* * 变量声明 newName:上传后在服务器上的文件名称 * * uploadFile:要上传的文件路径 actionUrl:服务器对应的程序路径 */ private String newName = ""; private String uploadFile = ""; private String actionUrl = "http://www.111cn.net/index.php";//这里定义你的上传路径
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = intent.getExtras(); newName = bundle.getString("fileName"); uploadFile = newName; String ok = post(actionUrl, newName); Toast.makeText(this, "OK!", Toast.LENGTH_LONG).show(); finish();
// // TODO Auto-generated catch block e.printStackTrace(); }
/** * * @param actionUrl * @param params * @param files * @return * @throws IOException */ public static String post(String actionUrl, String FileName) throws IOException {
String PREFIX = "--", LINEND = "rn"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8";
HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(5 * 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);
conn.getOutputStream());
if (FileName != "") {
sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name="file1"; filename="" + FileName + """ + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes());
byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.write(LINEND.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); int res = conn.getResponseCode(); InputStream in = null; if (res == 200) { in = conn.getInputStream(); int ch; StringBuilder sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } } return in == null ? null : in.toString(); } } |
具体调用方式如下:
代码如下 | 复制代码 |
jaddrobj = GetJsonAddr(String.valueOf(dLat), String.valueOf(dLong)); if (jaddrobj==null) { jaddrobj = SysUtil.GetJsonAddr(String.valueOf(dLat), String.valueOf(dLong)); } if (jaddrobj!=null) { jsobj = jaddrobj.getJSONObject("Status"); if(jsobj.getString("code").equals("200")){ jplacearr = jaddrobj.getJSONArray("Placemark"); jplaceobj = jplacearr.getJSONObject(0); address = jplaceobj.getString("address"); grobaldata.myAddress = address;// 当前地址放到全局变量里 grobaldata.curAddress = address;// 当前地址放到全局变量里 city = jplaceobj.getJSONObject("AddressDetails").getJSONObject("Country") .getJSONObject("AdministrativeArea").getJSONObject("Locality") .getString("LocalityName"); } else { rtValue = "error"; } } |
/**
* 根据经纬度反向解析地址,有时需要多尝试几次
* 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html
* 提交的地址解析请求次数是否有限制?) 如果在 24 小时时段内收到来自一个 IP 地址超过 2500 个地址解析请求, 或从一个 IP
* 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该
代码如下 | 复制代码 |
* IP 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。 * * @param latitude * 纬度 * @param longitude * 经度 * @return JSONObject * * @author lvqiyong */ /*例子如下: * { "name": "29.871398,121.5817", "Status": { "code": 200, "request": "geocode" }, "Placemark": [ { "id": "p1", "address": "中国浙江省宁波市江东区中兴路360号 邮政编码: 315040", "AddressDetails": { "Accuracy" : 8, "Country" : { "AdministrativeArea" : { "AdministrativeAreaName" : "浙江省", "Locality" : { "DependentLocality" : { "DependentLocalityName" : "江东区", "Thoroughfare" : { "ThoroughfareName" : "中兴路360号" } }, "LocalityName" : "宁波市" } }, "CountryName" : "中国", "CountryNameCode" : "CN" } }, "ExtendedData": { "LatLonBox": { "north": 29.8737610, "south": 29.8710630, "east": 121.5832290, "west": 121.5805310 } }, "Point": { "coordinates": [ 121.5818800, 29.8724120, 0 ] } } ] }*/ public static JSONObject GetJsonAddr(String latitude, String longitude) {
// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址 // 密钥可以随便写一个key=abc // output=csv,也可以是xml或json,采用默认的方式是output=json String url = String .format( "http://ditu.google.cn/maps/geo?key=abcdef&q=%s,%s", latitude, longitude); HttpGet httpGet = new HttpGet(url); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder();
try { response = client.execute(httpGet); /* HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); }*/ HttpEntity entity = response.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity .getContent())); String result = br.readLine(); while (result != null) { stringBuilder.append(result); result = br.readLine(); } } catch (ClientProtocolException e) { } catch (IOException e) { }
JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); } catch (JSONException e) { e.printStackTrace(); }
return jsonObject; } |
代码如下 | 复制代码 |
: import java.io.File; import android.content.Context; /** /** /** public AsyncImageView(Context context) { public AsyncImageView(Context context, AttributeSet attrs) { public AsyncImageView(Context context, AttributeSet attrs, int defStyle) { /** /** @Override @Override /** /** /** /** @Override @Override @Override /** File file = new File(fileName); /** /** |
下面是具体的代码
/**
* 向网站发送get请求,url需按照api要求写,返回取得的信息。
* //这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息
* @param url
* @param client
* @return String
* @author lvqiyong
*/
代码如下 | 复制代码 |
public static String getRequest1(String url, DefaultHttpClient client, String charset) throws Exception { String result = null; int statusCode = 0; HttpGet getMethod = new HttpGet(url); Log.d(TAG, "do the getRequest,url=" + url + ""); try { getMethod.setHeader("User-Agent", USER_AGENT); getMethod.setHeader("Cookie", "cy=" + value);//这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息 // 添加用户密码验证信息 // client.getCredentialsProvider().setCredentials( // new AuthScope(null, -1), // new UsernamePasswordCredentials(mUsername, mPassword));
HttpResponse httpResponse = client.execute(getMethod); // statusCode == 200 正常 statusCode = httpResponse.getStatusLine().getStatusCode(); Log.d(TAG, "statuscode = " + statusCode); // 处理返回的httpResponse信息 if (statusCode == 200) { result = retrieveInputStream(httpResponse.getEntity(), charset); Cookie cookie; String cookname,cookvalue; List<Cookie> cookies = client.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.i(TAG, "-------Cookie NONE---------"); } else { for (int i = 0; i < cookies.size(); i++) { // 保存cookie cookie = cookies.get(i); cookname = cookie.getName().trim(); cookvalue = cookie.getValue().trim(); if(cookname.equals("cy")){ name = cookname; value = cookvalue; } } } } else result = "networkerror"; } catch (ConnectTimeoutException e) {// 超时或网络连接出错 result = "timeouterror"; // e.printStackTrace(); } catch (ClientProtocolException e) { result = "networkerror"; // e.printStackTrace(); } catch (Exception e) { result = "readerror"; Log.e(TAG, e.getMessage()); throw new Exception(e); } finally { getMethod.abort(); } return result; } |
因为百事查需要,需要制作这样的更多分页按钮,因为感觉新浪微博的更多分页按钮比较好,就尝试做了一下。
1、首先需要考虑布局,就是footer的布局,如下:
代码如下 | 复制代码 |
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content" android:focusable="true" xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/loadmore" android:layout_centerVertical="true" android:layout_centerHorizontal="true"> <!-- <Button android:id="@+id/loadMoreButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="更多" /> --> <LinearLayout android:gravity="center" android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="fill_parent"> <ImageView android:background="@drawable/divider" android:layout_height="2.0dip" android:layout_width="fill_parent" /> </LinearLayout> <LinearLayout android:gravity="center" android:layout_gravity="center" android:orientation="horizontal" android:layout_centerVertical="true" android:layout_width="fill_parent" android:layout_height="60dip"> <TextView android:textSize="20.0sp" android:textColor="#ff545454" android:gravity="center" android:id="@id/tv_msg" android:text="更多" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <LinearLayout android:gravity="center" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="horizontal" android:id="@+id/llloading" android:layout_width="fill_parent"> <ProgressBar android:layout_gravity="center_vertical" android:id="@id/footprogress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminateBehavior="repeat" style="?android:progressBarStyleSmallInverse" /> <TextView android:textColor="#ff000000" android:gravity="left|center" android:padding="2.0px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="读取中" /> </LinearLayout> </LinearLayout> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="false" android:drawable="@drawable/listview_gradient" > </item> <item android:state_pressed="true" android:drawable="@drawable/list_selector_background_pressed" > </item> </selector>其中list_selector_background_pressed系统带的一个按钮在listview源代码中可以找到或sdk中也有 2、同时加载footer布局 list_footer = (LinearLayout)LayoutInflater.from(FansActivity.this).inflate(R.layout.sinalist_footer, null); tv_msg = (TextView)list_footer.findViewById(R.id.tv_msg); loading = (LinearLayout)list_footer.findViewById(R.id.llloading); //btloadmore = (Button)list_footer.findViewById(R.id.loadMoreButton); listView = getListView(); top_panel = (View)findViewById(R.id.fans_top); top_btn_left = (Button)top_panel.findViewById(R.id.top_btn_left); top_btn_right = (Button)top_panel.findViewById(R.id.top_btn_right); top_title = (TextView)top_panel.findViewById(R.id.top_title); listView.addFooterView(list_footer, null, false);//利用FooterVIew分页动态加载,参数false是不让选择 list_footer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { // Toast.makeText(FansActivity.this, "我将消失了", // Toast.LENGTH_SHORT).show(); //list_footer.setBackgroundColor(Color.YELLOW); //list_footer.invalidate(); new FansThread().start(); //tv_msg.setEnabled(false); tv_msg.setVisibility(View.GONE);// 隐藏更多提示的TextView loading.setVisibility(View.VISIBLE);// 显示最下方的进度条 } catch (Exception e) { e.printStackTrace(); } } }); |
效果如下
相关文章
php无刷新利用iframe实现页面无刷新上传文件(1/2)
利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25- 分享给大家php判断上传文件类型的方法,大家一起学习学习。/** * 读取文件前几个字节 判断文件类型 * @return String */ function checkTitle($filename){ $file=fopen($filename, "rb"); $bin=fread($file, 2); /...2015-10-21
- 这篇文章主要介绍了Vue使用formData格式类型上传文件的示例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
- 下面小编就为大家分享一篇c# FTP上传文件的实例代码,超简单哦~希望对大家有所帮助。一起跟随小编过来看看吧,...2020-06-25
- if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
- 这篇文章主要介绍了yii实现使用CUploadedFile上传文件的方法,结合具体的前端与后端处理代码实例分析了CUploadedFile类的使用方法,需要的朋友可以参考下...2015-12-31
阿里云OSS 通过表单直接上传文件 Post Policy例子
本文章为各位简单介绍阿里云OSS 通过表单直接上传文件 Post Policy例子,这个例子非常的简单只需要简单的像php一样就可以了,具体如下。 代码如下 复制代...2016-11-25- 本文给大家分享的是使用C++简单实现web服务器的代码,虽然非常的简陋,功能也很少,主要是为了更好的理解WEB服务器的工作原理,推荐给大家,也希望对大家能够有所帮助。...2020-04-25
- (作者:曹文龙、李维森) 目前,Web服务器的发展有三个主要趋势: 1.从HTML到XML(Extensible Markup Language-可扩展标记语言) HTML被称为“第一代Web语言”,如前面...2016-11-25
- 这篇文章主要介绍了PHP响应post请求上传文件的方法,涉及php针对post传输数据处理的相关技巧,需要的朋友可以参考下...2015-12-21
asp.net fileupload控件上传文件与多文件上传
这篇文章主要介绍了asp.net fileupload控件上传文件的方法,fileupload控件多文件上传,以及fileupload上传时实现文件验证的方法,需要的朋友可以参考下...2021-09-22- 一个网站,对于个人或小公司来说,前期直接上集群的开销是比较大的,那么采用单台服务器如何才能尽可能的提高网站效率呢?...2016-01-27
- 本篇文章主要介绍了解决ASP.NET Core Mvc文件上传限制问题,具有一定的参考价值,有需要的可以了解一下。...2021-09-22
- 可能会有不少朋友碰到一些问题就是上传文件时如果是英文倒好原文名不会有问题,如果是中文可能就会出现乱码了,今天我来给大家总结一下导致乱码php上传文件中文文件名乱...2016-11-25
- 本文章分享一篇关于android与Web服务器交互时的cookie使用实例有需要的同学可以参考一下。 下面是具体的代码 /** * 向网站发送get请求,url需按照api要求写,返回取...2016-09-20
- 上传文件或图片进行重命名是我们在php上传中会碰到的一个问题了,在重命名无非就是对你上传的文件生成一个随机的字符串了,包括有Md5,随机,或按时间日期来重命名了,下面我...2016-11-25
PHP fastcgi模式运行的PHP上传文件MaxRequestLen错误解决
在fastcgi模式下上传文件比较大时都会提示mod_fcgid: HTTP request length 135024 (so far) exceeds MaxRequestLen (131072)错误了,看意思是长度限制了,下面来给各位介...2016-11-25- 在php中文件上传我们都是利用表单的post来实例了,注意: 标签的 enctype 属性规定了在提交表单时要使用哪种内容类型。在表单需要二进制数据时,比如文件内容,请使用 \"mult...2016-11-25
- 本文章介绍了一个关于android通过http来实现文件上传功能,在服务器端我们是用php来实现的,有需要的朋友可以参考一下 代码如下 复制代码 <?...2016-09-20
- 好了我们来看看用php自带的ftp函数做的文件上传吧,上传文件我们会用到ftp_put把文件传送到服务器下面有两个上传的简单实例。 代码如下 复制代码 ...2016-11-25