简体   繁体   中英

Make POST request on Android app

I know this has been asked before but I'm struggling.. I barely know any Java, but want an app so I can do my POST request without opening my website.

So I've got this layout

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/editText2"
        android:text="Address:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/editText2"
        android:ems="10"
        android:inputType="phone" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText2"
        android:text="Phone:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_alignLeft="@+id/editText3"
        android:layout_below="@+id/editText3"
        android:ems="10"
        android:inputType="textMultiLine" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/editText4"
        android:text="Comments:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="15dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText4"
        android:layout_toLeftOf="@+id/editText4"
        android:text="Done"
        android:onClick="goToWeb(???);" />

</RelativeLayout>

and this Java:

package com.example.request;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainRequest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_request);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_request, menu);
        return true;
    }

    public void goToWeb() {
        /* open webpage - how? */
    }
}

I want to make this POST request to http://www.example.com when they click Done:

name: (content of @+id/editText1)
addr: (content of @+id/editText2)
phone: (content of @+id/editText3)
comment: (content of @+id/editText4)

I want the phone's browser to open, and perform the POST request (if that makes sense)

How do I do this?

I feel this is a relevant question with a good answer that you may want to consider looking at. Hope this helps.

Java - sending HTTP parameters via POST method easily

EDIT: Actually I found an ever better one for Android specifically:

Android, Java: HTTP POST Request

Okay so I guess you're also kinda confused about how to get the text from your text fields you created. Here is another stackoverflow question that can help you:

Get Value of a Edit Text field

You have some edittext fields set up so you just have to store them in a variable (you can get that value by using findViewById(R.id.idOfEditText) and storing it in a variable. Now with that variable, you just need to call .getText() and then you have the String and can do whatever you need to do with it (such as sending it via POST).

Try this Class MainRequest

package com.example.teststack;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainRequest extends Activity {

    EditText textPersonName = null;
    EditText textPostalAddress = null;
    EditText phone = null;
    EditText textMultiLine = null;
    Button submit = null;
    String action = "http://www.omokoroacomputerhelp.com/";
    HttpPost httpRequest = null;
    List<NameValuePair> params = null;
    HttpResponse httpResponse = null;
    WebView webView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_request);
        textPersonName = (EditText) findViewById(R.id.personName);
        textPostalAddress = (EditText) findViewById(R.id.postalAddress);
        phone = (EditText) findViewById(R.id.phone);
        textMultiLine = (EditText) findViewById(R.id.multiLine);
        submit = (Button) findViewById(R.id.submit);
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                httpRequest = new HttpPost(action);
                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", textPersonName
                        .getText().toString()));
                params.add(new BasicNameValuePair("phone", phone.getText()
                        .toString()));
                params.add(new BasicNameValuePair("addr", textPostalAddress
                        .getText().toString()));
                params.add(new BasicNameValuePair("comment", textMultiLine
                        .getText().toString()));
                try {
                    // send http request
                    httpRequest.setEntity(new UrlEncodedFormEntity(params,
                            HTTP.UTF_8));
                    // get http response
                    httpResponse = new DefaultHttpClient().execute(httpRequest);
                    //
                    Intent gotoIntent = new Intent(MainRequest.this,
                            Webpage.class);
                    gotoIntent.putExtra("source",
                            EntityUtils.toString(httpResponse.getEntity()));
                    startActivity(gotoIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_request, menu);
        return true;
    }

}

and Webpage

package com.example.teststack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;

public class Webpage extends Activity {
    WebView webView;

    final String mimeType = "text/html";

    final String encoding = "utf-8";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webpage);
        Intent webPageIntent = getIntent();
        String htmlSource = webPageIntent.getStringExtra("source");
        webView = (WebView) findViewById(R.id.webview);
        webView.loadData(htmlSource, mimeType, encoding);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_webpage, menu);
        return true;
    }
}

and activity_main_request.xml

<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" >

    <EditText
        android:id="@+id/personName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/postalAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/personName"
        android:layout_below="@+id/personName"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/postalAddress"
        android:text="Address:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/postalAddress"
        android:ems="10"
        android:inputType="phone" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/postalAddress"
        android:text="Phone:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/multiLine"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_alignLeft="@+id/phone"
        android:layout_below="@+id/phone"
        android:ems="10"
        android:inputType="textMultiLine" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/multiLine"
        android:text="Comments:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="15dp" />

    <Button
        android:id="@+id/submit"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/multiLine"
        android:layout_toLeftOf="@+id/multiLine"
        android:text="Done" />

</RelativeLayout>

and activity_webpage.xml

<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" >

   <WebView  
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</RelativeLayout>

and AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teststack"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainRequest"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Webpage"
            android:label="@string/title_activity_webpage" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Try using the NameValuePair .. I am giving the code which i used in my app to do Http Post

public String postData(String url, String xmlQuery) {



        final String urlStr = url;
        final String xmlStr = xmlQuery;
        final StringBuilder sb  = new StringBuilder();


        Thread t1 = new Thread(new Runnable() {

            public void run() {

                HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();

                HttpPost httppost = new HttpPost(urlStr);


                try {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);

                    Log.d("Vivek", response.toString());

                    HttpEntity entity = response.getEntity();
                    InputStream i = entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReader isr = new InputStreamReader(i);

                    BufferedReader br = new BufferedReader(isr);

                    String s = null;


                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }


                    Log.d("Check Now",sb+"");




                } catch (ClientProtocolException e) {

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

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        System.out.println("Getting from Post Data Method "+sb.toString());

        return sb.toString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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