在Android应用上发出POST请求

时间:2012-08-26 02:58:05

标签: java android eclipse

我知道之前已经问过这个问题但是我很挣扎......我几乎不知道任何Java,但想要一个应用程序,所以我可以在不打开我的网站的情况下完成我的POST请求。

所以我有这个布局

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

和这个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? */
    }
}

我想在点击完成后向http://www.example.com发出此POST请求:

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

我希望手机的浏览器打开,然后执行POST请求(如果有意义的话)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

我觉得这是一个相关的问题,你可能需要考虑一个好的答案。希望这会有所帮助。

Java - sending HTTP parameters via POST method easily

编辑:其实我发现了一个更好的Android专用:

Android, Java: HTTP POST Request

好吧所以我猜你也对如何从你创建的文本字段中获取文本感到困惑。这是另一个可以帮助您的stackoverflow问题:

Get Value of a Edit Text field

您设置了一些edittext字段,因此您只需将它们存储在变量中(您可以使用findViewById(R.id.idOfEditText)获取该值并将其存储在变量中。现在使用该变量,您只需要调用.getText()然后你有了String并可以做任何你需要做的事情(比如通过POST发送)。

答案 1 :(得分:0)

尝试此类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;
    }

}

和网页

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;
    }
}

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

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

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

答案 2 :(得分:0)

尝试使用NameValuePair ..我正在提供我在我的应用中使用的代码来执行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();
    }