Android模拟表单提交(上传文件)

经过form表单进行上传文件 php


<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>



利用android api自带的httpclient进行模仿web中的form表单进行提交



public class MainActivity extends Activity {

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		new Thread() {
			public void run() {
				try {
					doUPloadFile();
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	public HttpClient createClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.DEFAULT_CONTENT_CHARSET);
		params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
		params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000);
		params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30 * 1000);

		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

		return new DefaultHttpClient(conMgr, params);
	}

	void doUPloadFile() throws Exception {
		// 须要上传的文件
		File file = new File("/storage/sdcard0/test.png");
		FileInputStream fis = new FileInputStream(file);
		HttpClient httpclient = createClient();
		String url = "";

		MultipartEntity me = new MultipartEntity();//须要下载第三方jar包(httpmime.jar)
		me.addPart("file", new InputStreamBody(fis, file.getName()));

		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(me);

		HttpResponse httpResponse = httpclient.execute(httpPost);

		int code = httpResponse.getStatusLine().getStatusCode();
		log("http status code:" + code);
		if (code == HttpStatus.SC_OK) {
			String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
			// 上传的结果,能够使json,或者是返回上传后文件的的url
			Log.v("result = " + result);
			Log.v("上传成功");
		}
	}
}
相关文章
相关标签/搜索