从机器人的仿真器POST请求到服务器 [英] POST request from emulator of android to a server

查看:119
本文介绍了从机器人的仿真器POST请求到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想单个图像发布到服务器


  • 有一个图像视图和一个按钮

  • 我想张贴图像服务器上的按钮
  • 的点击

我曾尝试


MainActivity.java

 公共类MainActivity延伸活动{    按钮提交;
    ProgressDialog pDialog;    ImageView的ImageView的;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        提交=(按钮)findViewById(R.id.SUBMIT_BUTTON_ID);        ImageView的=(ImageView的)findViewById(R.id.imageView1);        submit.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根
                新MainTest()执行();
            }
        });
    }    / **
     *方法张贴图像到服务器。
     * U将不得不改变,这将接受图像数据的URL。
     *引发IOException
     * /
    公共无效postImageData()抛出IOException异常
    {
         //一些随机ID。 ü可以根据要求改变这种
        字符串NEWURL =? +键=+新的随机()nextLong()。
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(http://54.218.73.244:7002/Details/+ NEWURL);        //之后转换位图drawble为位图,并得到字串发送到服务器
        位图的位图=((BitmapDrawable)imageView.getDrawable())getBitmap();
        。字符串DIR = Environment.getExternalStorageDirectory()的toString();
        FOS的OutputStream = NULL;        档案文件=新的文件(目录temp.JPEG);
        FOS =新的FileOutputStream(文件);
        BOS的BufferedOutputStream =新的BufferedOutputStream(FOS);
        bitmap.com preSS(Bitmap.Com pressFormat.JPEG,100,BOS);        bos.flush();
        bos.close();        MultipartEntity实体=新MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);        文件MFILE =新的文件(目录temp.JPEG);
        FileBody encFile =新FileBody(MFILE,图像/ JPEG);
        entity.addPart(为imageData,encFile);
        //另外一个键/值参数
        //entity.addPart(\"UserId,新StringBody(用户ID));        httppost.setEntity(实体);        HttpClient的客户端=新DefaultHttpClient();
        HTT presponse响应= httpclient.execute(httppost);        字符串数据= EntityUtils.toString(response.getEntity());
        的System.out.println(响应数据:+数据);
    }    公共类MainTest扩展的AsyncTask<字符串,整数,字符串> {        @覆盖
        在preExecute保护无效(){
            pDialog =新ProgressDialog(MainActivity.this);
            pDialog.setMessage(中..);
            pDialog.setIndeterminate(真);
            pDialog.setCancelable(假);
            pDialog.show();
        }        @覆盖
        保护字符串doInBackground(字符串... PARAMS){            尝试{
                postImageData();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }            返回null;
        }        @覆盖
        保护无效onPostExecute(字符串结果){
            // TODO自动生成方法存根            super.onPostExecute(结果);
            //数据= jobj.toString();
            pDialog.dismiss();        }    }}

activity_main.xml中

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直
    工具:上下文=MainActivity。>    < ImageView的
        机器人:ID =@ + ID / imageView1
        机器人:layout_width =135​​dp
        机器人:layout_height =181dp
        机器人:layout_alignParentTop =真
        机器人:layout_marginTop =32dp
        机器人:可点击=假
        机器人:SRC =@绘制/图像/>    <按钮
        机器人:ID =@ + ID / SUBMIT_BUTTON_ID
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_marginBottom =47dp
        机器人:文字=提交/>< / LinearLayout中>

清单

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.example.datapostingproject
    安卓版code =1
    机器人:=的versionName1.0>    <用途-SDK
        安卓的minSdkVersion =8
        机器人:targetSdkVersion =17/>
    <使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
    <使用许可权的android:NAME =android.permission.INTERNET对/>
    <使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/>    <应用
        机器人:allowBackup =真
        机器人:图标=@绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名字=com.example.datapostingproject.MainActivity
            机器人:标签=@字符串/ APP_NAME>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>                <类机器人:名字=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
    < /用途>< /清单>

注意:我还添加了必需的MIME jar文件太


此外,我已经检查服务器是否正在运行,或者不

我已经使用镀铬的邮递员来测试这个

做这个测试之后....我可以看到服务器中的图像....有了这个,我验证服务器是否正在运行的这条路线


有什么问题


  • 当我运行这个程序,从做一个POST请求到服务器
    机器人(我使用Android模拟器,使要求)

  • 我无法发送图像

  • 我需要从模拟器这项任务的工作


由经验丰富的专业人员任何输入



解决方案

 最后弦乐METHOD_NAME =服务名称; // 我们的
    最后弦乐SOAP_ACTION =htt​​p://tempuri.org/ServiceName;
    字符串结果= NULL;    SoapObject要求=新SoapObject空间(namespace,METHOD_NAME);
    request.addProperty(IMEI,IMEI);
    request.addProperty(asscd,asscd);    SoapPrimitive响应=无效;    SoapSerializationEnvelope信封=新SoapSerializationEnvelope(
                                                    SoapEnvelope.VER11);
                    envelope.dotNet = TRUE;
                    envelope.setOutputSoapObject(请求);
                    尝试{                                    HttpTransportSE androidHttpTransport =新HttpTransportSE(URL);                                    androidHttpTransport.call(SOAP_ACTION,信封);                                    响应=(SoapPrimitive)envelope.getResponse();
                                                 //这里SoapPrimitive的重要组成部分
                                    结果= response.toString();                    }赶上(例外五){
                                    e.printStackTrace();
                    }
        返回结果;

I am trying to post a single image to server

  • there is one image view and one button
  • I am trying to post image to server on click of the button

What i have tried ?


MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

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

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }



    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException 
     */
    public void postImageData() throws IOException
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("imageData", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId)); 

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);                

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                postImageData();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

activity_main.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="135dp"
        android:layout_height="181dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="32dp"
        android:clickable="false"
        android:src="@drawable/image" />

    <Button
        android:id="@+id/SUBMIT_BUTTON_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="47dp"
        android:text="SUBMIT" />

</LinearLayout>

manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.datapostingproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.datapostingproject.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>

Note: I have also added the required mime jar file too


Also i have checked whether server is working or not

i have used postman of chrome to test this

After doing this test .... I can see the image in server.... with this i validate that server is running for this route


What is the problem::

  • When i run this program and make a post request to server from android ( i am using android emulator to make request)
  • i cannot post the images
  • i need to make this task work from emulator

Any Inputs from experienced professionals


解决方案

    final String METHOD_NAME = "ServiceName"; // our
    final String SOAP_ACTION = "http://tempuri.org/ServiceName";
    String result = null;

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("IMEI", Imei);
    request.addProperty("asscd", asscd);

    SoapPrimitive response = null;

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                                                    SoapEnvelope.VER11);
                    envelope.dotNet = true;
                    envelope.setOutputSoapObject(request);
                    try {

                                    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                                    androidHttpTransport.call(SOAP_ACTION, envelope);

                                    response = (SoapPrimitive) envelope.getResponse();
                                                 //here SoapPrimitive is an important part
                                    result = response.toString();

                    } catch (Exception e) {
                                    e.printStackTrace();
                    }


        return result;

这篇关于从机器人的仿真器POST请求到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆