안 드 로 이 드 는 servlet 서버 를 통 해 파일 을 휴대 전화 에 저장 합 니 다.
서버 쪽:(휴대폰 과 컴퓨터 가 연 결 된 동일 한 와 이 파이)
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");//// ,
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()
{// , Base64
// String imgFile = "d://test.jpg";//
//String imgFile="F://upload//1.jpg";////
// String imgFile="F://upload// .ppt";////
String imgFile="F://upload// .mp3";//
// String imgFile="F://upload//upload.rar";//
InputStream in = null;
byte[] data = null;
//
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
// Base64
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// Base64
} ///GetImageStr
}
휴대폰 단말기:
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;// 10
private static final int SO_TIMEOUT = 10*60 * 1000; // 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
Log.i("button1", "button1");
fun_HttpPost();
}
});
}
public void fun_HttpPost() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO
String urlStr = "http://192.168.0.102:8080/download/servlet/download";
HttpPost request = new HttpPost(urlStr);
try {
HttpClient client = getHttpClient();
//
HttpResponse response = client.execute(request);
//
if (response.getStatusLine().getStatusCode() == 200) {
//
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
public static boolean GenerateImage(String imgStr)
{ // Base64
if (imgStr == null) //
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)
{//
b[i]+=256;
}
}
// jpeg
// String imgFilePath = "d://222.jpg";//
// String imgFilePath = "F://upload//1_2.jpg";///
//String imgFilePath = "F://upload// _2.ppt";//
// String imgFilePath="F://upload//upload_2.rar";
// String imgFilePath="/sdcard/1spray/1_2.jpg";//
// String imgFilePath = "/sdcard/1spray/ _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,
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" />
<!-- -->
<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 -->
<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>
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.