简体   繁体   English

从android的模拟器到服务器的POST请求

[英]POST request from emulator of android to a server

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 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 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 注意 :我也添加了必需的mime jar文件


Also i have checked whether server is working or not 我也检查了服务器是否在工作

i have used postman of chrome to test this 我用postman of chrome来测试

在此处输入图片说明

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) 当我运行此程序并从android向服务器发出发布请求时(我正在使用android模拟器发出请求)
  • 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM