首页 > 代码库 > android 随手记之文件+参数上传请求
android 随手记之文件+参数上传请求
第一步:需要两个jar的支持,稍后下面给会出下载地址。
第二步:建立一个工程
下面贴出最主要的代码
package com.example.testpaizhao;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class testphone extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.face_recognition_activity);
new Thread(){
public void run() {
try {
mai();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
private void mai() throws Exception{
// 上传图片到服务器
HttpPost httpPost = new HttpPost(服务器地址);
// 设置传递参数
File file1 = new File("/mnt/sdcard/yangtest.txt");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("vice_id",
new StringBody("1", Charset
.forName(org.apache.http.protocol.HTTP.UTF_8)));
reqEntity.addPart("m",
new StringBody("15261651603", Charset
.forName(org.apache.http.protocol.HTTP.UTF_8)));
reqEntity.addPart("f",
new StringBody("66666666666", Charset
.forName(org.apache.http.protocol.HTTP.UTF_8)));
// if (!file1.getAbsoluteFile().equals(""))
// {
// FileBody fileBody = new FileBody(file1);
// reqEntity.addPart("pic", fileBody);
// }
//
// StringBody type = new StringBody("wish");
// reqEntity.addPart("type", type);
// if( type.equals("wish") ){
// StringBody temp = new StringBody("1");
// reqEntity.addPart("temp", temp);
// }
// else
// {
// StringBody temp = new StringBody("");
// reqEntity.addPart("temp", temp);
// }
httpPost.setEntity(reqEntity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpPost);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println("yes!");
Log.i("test","no"+strResult.toString());
}
else
{
Log.i("test","no");
}
}
}
该类可以直接上传文件+String的信息 根据自己需要自己改改吧
最后别忘了 在清单文件中加网络权限
android 随手记之文件+参数上传请求