android通過servlet服務(wù)器保存文件到手機(jī)
本文實(shí)例為大家分享了android通過servlet服務(wù)器保存文件到手機(jī)的具體代碼,供大家參考,具體內(nèi)容如下
服務(wù)器端:(手機(jī)和電腦連接的同一個(gè)WIFI)
package com;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Encoder;
public class download extends HttpServlet {
/**
* Constructor of the object.
*/
public download() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the GET method");
// out.println(" </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
//request.setCharacterEncoding("utf-8");////這句至關(guān)重要,不然中文的文件名稱顯示亂碼
PrintWriter out = response.getWriter();
// out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println(" </BODY>");
// out.println("</HTML>");
out.print(GetImageStr());///輸出文件的字符串
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
public static String GetImageStr()
{//將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對(duì)其進(jìn)行Base64編碼處理
// String imgFile = "d://test.jpg";//待處理的圖片
//String imgFile="F://upload//1.jpg";////可以
// String imgFile="F://upload//軟工大作業(yè).ppt";////可以
String imgFile="F://upload//愛的勇氣.mp3";//不可以
// String imgFile="F://upload//upload.rar";//可以
InputStream in = null;
byte[] data = null;
//讀取圖片字節(jié)數(shù)組
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//對(duì)字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64編碼過的字節(jié)數(shù)組字符串
} ///GetImageStr
}
手機(jī)端:
package com.example.getfile_2;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private static final int REQUEST_TIMEOUT = 5 * 1000;// 設(shè)置請(qǐng)求超時(shí)10秒鐘
private static final int SO_TIMEOUT = 10*60 * 1000; // 設(shè)置請(qǐng)求超時(shí)時(shí)間10秒鐘
private static final int LOGIN_OK = 1;
private Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自動(dòng)生成的方法存根
Log.i("button1", "button1");
fun_HttpPost();
}
});
}
public void fun_HttpPost() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO 自動(dòng)生成的方法存根
String urlStr = "http://192.168.0.102:8080/download/servlet/download";
HttpPost request = new HttpPost(urlStr);
try {
HttpClient client = getHttpClient();
// 執(zhí)行請(qǐng)求返回相應(yīng)
HttpResponse response = client.execute(request);
// 判斷是否請(qǐng)求成功
if (response.getStatusLine().getStatusCode() == 200) {
// 獲得響應(yīng)信息
String responseMessage = EntityUtils.toString(response
.getEntity());
Log.i("responseMessage", responseMessage + ",長度:"
+ responseMessage.length());
GenerateImage(responseMessage);
Log.i("生成成功", "生成成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}// //run()
}).start();
}// /fun_register()
//base64字符串轉(zhuǎn)化成圖片
public static boolean GenerateImage(String imgStr)
{ //對(duì)字節(jié)數(shù)組字符串進(jìn)行Base64解碼并生成圖片
if (imgStr == null) //圖像數(shù)據(jù)為空
return false;
Decoder.BASE64Decoder decoder = new Decoder.BASE64Decoder();
try
{
//Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//調(diào)整異常數(shù)據(jù)
b[i]+=256;
}
}
//生成jpeg圖片
// String imgFilePath = "d://222.jpg";//新生成的圖片
// String imgFilePath = "F://upload//1_2.jpg";///可以
//String imgFilePath = "F://upload//軟工大作業(yè)_2.ppt";//可以
// String imgFilePath="F://upload//upload_2.rar";
// String imgFilePath="/sdcard/1spray/1_2.jpg";//可以
// String imgFilePath = "/sdcard/1spray/軟工大作業(yè)_2.ppt";//可以
String imgFilePath ="/sdcard/1spray/愛的勇氣_2.mp3";//9M不行了?????
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
// 初始化HttpClient,并設(shè)置超時(shí)
public HttpClient getHttpClient() {
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}// /public HttpClient getHttpClient()
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginLeft="25dp"
android:layout_marginTop="142dp"
android:layout_toRightOf="@+id/textView1"
android:text="ButtonPost" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="34dp"
android:text="ButtonGet" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.getfile_2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="16" /> <!-- 使用網(wǎng)絡(luò)功能所需權(quán)限 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- SDK離線地圖和cache功能需要讀寫外部存儲(chǔ)器 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>




以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android?進(jìn)入Activity時(shí)如何禁止彈出軟鍵盤輸入法
這篇文章主要介紹了Android?進(jìn)入Activity時(shí)如何禁止彈出軟鍵盤輸入法,文章圍繞主題展開具體內(nèi)容,需要的小伙伴可以參考一下2022-05-05
Android實(shí)現(xiàn)多線程下載圖片的方法
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多線程下載圖片的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
Material Design系列之Behavior實(shí)現(xiàn)Android知乎首頁
這篇文章主要為大家詳細(xì)介紹了Material Design系列之Behavior實(shí)現(xiàn)Android知乎首頁的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
Android大作業(yè)功能設(shè)計(jì)之自動(dòng)登錄和記住密碼
SharedPreferences是Android平臺(tái)上一個(gè)輕量級(jí)的存儲(chǔ)類,主要是保存一些常用的配置參數(shù),它是采用xml文件存放數(shù)據(jù)的,文件存放在"/data/data<package?name>/shared_prefs"目錄下,由于SharedPreferences是一個(gè)接口,而且在這個(gè)接口里沒有提供寫入數(shù)據(jù)和讀取數(shù)據(jù)的能力2023-01-01
listview與SQLite結(jié)合實(shí)現(xiàn)記事本功能
這篇文章主要為大家詳細(xì)介紹了listview與SQLite結(jié)合實(shí)現(xiàn)記事本功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Android使用SwipeListView實(shí)現(xiàn)類似QQ的滑動(dòng)刪除效果
這篇文章主要介紹了Android使用SwipeListView實(shí)現(xiàn)類似QQ的滑動(dòng)刪除效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
Flutter StatefulBuilder實(shí)現(xiàn)局部刷新實(shí)例詳解
這篇文章主要為大家介紹了Flutter StatefulBuilder實(shí)現(xiàn)局部刷新實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Android onLoadFinished與onLoaderReset回調(diào)詳解及實(shí)例
這篇文章主要介紹了Android onLoadFinished與onLoaderReset回調(diào)詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-03-03

