第二篇(wcfとandroidピクチャーアップロードダウンロード)
8577 ワード
古いしきたりは余計なことを言わないで,直接テーマに入る.
注意:wcfはrestスタイルを使用し、jsonデータを転送します.画像はbase 64で符号化され、androidはcommon-codec-1.5.jarでbase 64で符号化されます.
サーバ側
wcfインタフェース:
インタフェースの実装:
クライアント
注意:wcfはrestスタイルを使用し、jsonデータを転送します.画像はbase 64で符号化され、androidはcommon-codec-1.5.jarでbase 64で符号化されます.
サーバ側
wcfインタフェース:
namespace Test
{
// : "IService1", Web.config "IService1" 。
[ServiceContract]
public interface IService1
{
// :
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "update_pictrue",BodyStyle=WebMessageBodyStyle.WrappedRequest,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
string update_pictrue(string name, string content, string type);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "down_pictrue", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string down_pictrue(string name);
}
}
インタフェースの実装:
namespace Test
{
// : “Service1”, Web.config .svc “Service1” 。
public class Service1 : IService1
{
#region IService1
public string update_pictrue(string name,string content, string type)
{
// throw new NotImplementedException();
if (type != ".jpg" && type != ".gif")
{
return " ";
}
else
{
string imgFilePath = @"F:\Wcf_teach\pictrue_update_down\Test\update_pictrue\" + name;
if (!File.Exists(imgFilePath))
{
try
{
byte[] ms_content = Convert.FromBase64String(content);
FileStream fs = File.Open(imgFilePath, FileMode.OpenOrCreate);
fs.Write(ms_content, 0, ms_content.Length);
fs.Close();
return " ";
}
catch (Exception ex)
{
return " ";
}
}
else
{
return " ";
}
}
}
public string down_pictrue(string name)
{
// throw new NotImplementedException();
string imgFilePath = @"F:\Wcf_teach\pictrue_update_down\Test\update_pictrue\" + name;
if (File.Exists(imgFilePath))
{
System.IO.FileStream fs = new System.IO.FileStream(imgFilePath, System.IO.FileMode.Open);
int i = (int)fs.Length;
byte[] content = new byte[i];
fs.Read(content, 0, i);
string result = Convert.ToBase64String(content);
fs.Close();
return result;
}
else
{
throw new Exception(" ");
}
}
#endregion
}
}
クライアント
public class pictrue_update_down extends Activity {
private Button update_btn;
private Button down_btn;
private ImageView img_img;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findAll();
bind();
}
public void findAll() {
update_btn = (Button) this.findViewById(R.id.update_btn);
down_btn = (Button) this.findViewById(R.id.down_btn);
img_img = (ImageView) this.findViewById(R.id.img_img);
}
public void bind() {
update_btn.setOnClickListener(mylistener);
down_btn.setOnClickListener(mylistener);
}
private View.OnClickListener mylistener = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.update_btn:
Thread th1 = new Thread(new mythread());
th1.start();
break;
case R.id.down_btn:
Thread th2 = new Thread(new mythread_down());
th2.start();
break;
default:
break;
}
}
};
Handler hd = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
// super.handleMessage(msg);
if (msg.what == 123) {
String jason = msg.obj.toString();
String filepath = Environment.getExternalStorageDirectory()
+ File.separator + jason;
Bitmap bitmap1 = BitmapFactory.decodeFile(filepath);
img_img.setImageBitmap(bitmap1);
}
}
};
class mythread_down implements Runnable {
public void run() {
// TODO Auto-generated method stub
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(
"http://192.168.1.229/Test/service1.svc/down_pictrue");
HttpResponse hr = null;
JSONObject jo1 = new JSONObject();
try {
jo1.put("name", "999.jpg");
StringEntity se = new StringEntity(jo1.toString(), HTTP.UTF_8);
se.setContentType("application/json");
hp.setEntity(se);
hr = hc.execute(hp);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String strResp = null;
if (hr.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
try {
strResp = EntityUtils.toString(hr.getEntity());
File f = new File("//sdcard//999.jpg");
if (!f.exists()) {
f.createNewFile();
FileOutputStream fos=new FileOutputStream(f);
byte[] content= Base64.decodeBase64(strResp.getBytes());
fos.write(content);
fos.flush();
Message msg=hd.obtainMessage(123);
msg.obj="//sdcard//999.jpg";
hd.sendMessage(msg);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(pictrue_update_down.this, " ",
Toast.LENGTH_LONG).show();
}
}
}
class mythread implements Runnable {
public void run() {
// TODO Auto-generated method stub
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(
"http://192.168.1.229/Test/service1.svc/update_pictrue");
HttpResponse hr;
String path = "//sdcard//999.jpg";
File f = new File(path);
if (f.exists()) {
// System.out.println("successful");
try {
int ig = (int) f.length();
byte[] content = new byte[ig];
FileInputStream fis;
fis = new FileInputStream(f);
fis.read(content, 0, ig);
String jason = new String(Base64.encodeBase64(content));
JSONObject jo1 = new JSONObject();
jo1.put("name", "999.jpg");
jo1.put("content", jason);
jo1.put("type", ".jpg");
StringEntity se = new StringEntity(jo1.toString(),
HTTP.UTF_8);
se.setContentType("application/json");
hp.setEntity(se);
hr = hc.execute(hp);
String strResp = null;
if (hr.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
strResp = EntityUtils.toString(hr.getEntity());
} else {
strResp = "$no_found_date$";
}
Toast.makeText(pictrue_update_down.this, strResp,
Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
hp.abort();
}
}
}
}
}