Android 代码未命中服务器端
我正在尝试将图像从android mobile发送到.NET服务器,android代码:-Android 代码未命中服务器端,android,Android,我正在尝试将图像从android mobile发送到.NET服务器,android代码:- package com.example.imageupload; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.
package com.example.imageupload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
InputStream mInputStream;
String mUrl = "http://10.0.2.2:49246/WebSite1/";
// Async task helps to run network operations in Non-UI thread..
private class GetRouteInfo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
try
{
//resize the bitmap...
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/android.jpg";
Bitmap bitmap = resizeBitMapImage1(path, 800, 600);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30, stream);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image_data", Base64.encodeToString(stream.toByteArray(),Base64.NO_WRAP)));
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", "TrueSeeImage"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("response", response1.toString());
Log.i("DataUploaderOffline_Image ","Status--> Completed");
}
catch (Exception e) {
Log.i("SvcMgr", "Service Execution Failed!", e);
}
finally {
Log.i("SvcMgr", "Service Execution Completed...");
}
return null;
}
@Override
protected void onCancelled() {
Log.i("SvcMgr", "Service Execution Cancelled");
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("SvcMgr", "Service Execution cycle completed");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetRouteInfo().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
mInputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
System.out.println("contentLength : " + contentLength);
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = mInputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
mInputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
System.out.println("Result : " + res);
}
return res;
}
// Method to compress image..
// Input : filepath, target width, target height..
// Output : resized bitmap image..
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,int targetHeight) {
Bitmap bitMapImage = null;
try {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
sampleSize = scaleByHeight ? options.outHeight / targetHeight
: options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d,Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
} catch (Exception ex) {
}
return bitMapImage;
}
}
package com.example.imageupload;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入android.app.Activity;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.BitmapFactory.Options;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Environment;
导入android.os.StrictMode;
导入android.util.Base64;
导入android.util.Log;
导入android.view.Menu;
公共类MainActivity扩展了活动{
输入流mInputStream;
字符串mUrl=”http://10.0.2.2:49246/WebSite1/";
//异步任务有助于在非UI线程中运行网络操作。。
私有类GetRouteInfo扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的Void doInBackground(Void…参数)
{
尝试
{
//调整位图的大小。。。
字符串路径=Environment.getExternalStorageDirectory().getAbsolutePath()+“/android.jpg”;
位图位图=resizeBitMapImage1(路径,800600);
ByteArrayOutputStream=新建ByteArrayOutputStream();
压缩(位图.CompressFormat.JPEG,30,流);
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“image_data”,Base64.encodeToString(stream.toByteArray(),Base64.NO_WRAP));
stream.flush();
stream.close();
bitmap.recycle();
添加(新的BasicNameValuePair(“文件名”、“TrueSeeImage”);
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(mUrl);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1=httpclient.execute(httppost);
Log.i(“response”,response1.toString());
Log.i(“DataUploaderOffline_图像”,“状态-->已完成”);
}
捕获(例外e){
Log.i(“SvcMgr”,“服务执行失败!”,e);
}
最后{
Log.i(“SvcMgr”,“服务执行完成…”);
}
返回null;
}
@凌驾
受保护的void onCancelled(){
Log.i(“SvcMgr”,“服务执行已取消”);
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
Log.i(“SvcMgr”,“服务执行周期已完成”);
}
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建GetRouteInfo().execute();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
返回true;
}
公共字符串convertResponseToString(HttpResponse响应)引发IllegalStateException,IOException{
字符串res=“”;
StringBuffer=新的StringBuffer();
mInputStream=response.getEntity().getContent();
int contentLength=(int)response.getEntity().getContentLength();//获取内容长度…。。
System.out.println(“contentLength:+contentLength”);
if(contentLength<0){
}
否则{
字节[]数据=新字节[512];
int len=0;
尝试
{
而(-1!=(len=mInputStream.read(data)))
{
append(新字符串(数据,0,len));//转换为字符串并追加到stringbuffer…。。
}
}
捕获(IOE异常)
{
e、 printStackTrace();
}
尝试
{
mInputStream.close();//关闭流…。。
}
捕获(IOE异常)
{
e、 printStackTrace();
}
res=buffer.toString();//正在将stringbuffer转换为字符串…。。
System.out.println(“结果:+res”);
}
返回res;
}
//方法压缩图像。。
//输入:文件路径、目标宽度、目标高度。。
//输出:调整大小的位图图像。。
公共静态位图大小BitMapImage1(字符串文件路径、int-targetWidth、int-TargetLight){
位图bitMapImage=null;
试一试{
选项=新选项();
options.inJustDecodeBounds=true;
解码文件(文件路径,选项);
双重抽样=0;
布尔scaleByHeight=Math.abs(options.outHeight-targetHeight)>=Math
.abs(可选。外宽-目标宽);
如果(options.outHeight*options.outWidth*2>=1638){
sampleSize=scaleByHeight?选项。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(Server.MapPath("~/Data")))
{
}
else
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Data"));
}
if (Request.InputStream.Length != 0 && Request.InputStream.Length < 32768)
{
Response.ContentType = "text/plain";
string c = Request.Form["image_data"];
string FileName = Request.Form["FileName"];
byte[] bytes = Convert.FromBase64String(c);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
String Fname = FileName + ".jpeg";
image.Save(Server.MapPath("save\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
}
}
}