android发布http应用程序错误

时间:2012-01-20 10:49:17

标签: android http-post

我正在尝试在Android应用中获取post get方法,但有些我如何得到错误

Bellow是应用中使用的主要文件。

activity.java

package com.aaaaaa.httptest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 org.apache.http.util.ByteArrayBuffer;
import org.postandget.R;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HttpgettutorialActivity extends Activity {
    TextView txtvw;
    String text;

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

        txtvw=(TextView)findViewById(R.id.textview);
        text = "";

        postData();
    }

    public void postData(){  
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://webhome.com/index.php?id=69887");  

        try {
            // Add your data
            List nameValuePairs = new ArrayList(1);
            nameValuePairs.add(new BasicNameValuePair("data1", "dataValue"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(20);

            int current = 0;

            while((current = bis.read()) != -1){
                baf.append((byte)current);
            }  

            /* Convert the Bytes read to a String. */
            text = new String(baf.toByteArray());
            txtvw.setText(text);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
}

main.java

package com.aaaaaa.httptest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.postandget.R;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class main extends Activity {

    TextView tv;
    String text;

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

        tv=(TextView)findViewById(R.id.textview);
        text    = "";

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

    public void postData() throws JSONException{  
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://webhome.com/index.php?id=79370");
        JSONObject json = new JSONObject();

        try {
            // JSON data:
            json.put("name", "Heman");
            json.put("position", "Universe");

            JSONArray postjson=new JSONArray();
            postjson.put(json);

            // Post the data:
            httppost.setHeader("json",json.toString());
            httppost.getParams().setParameter("jsonpost",postjson);

            // Execute HTTP Post Request
            System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);

            // for JSON:
            if(response != null)
            {
                InputStream is = response.getEntity().getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                text = sb.toString();
            }

            tv.setText(text);

        }catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.postandget"
      android:versionCode="1"
      android:versionName="1.0">
<application android:icon="@drawable/ic_launcher"
             android:label="@string/app_name">
<activity android:name=".main"
          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>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
<ScrollView android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/scrollView1">
<LinearLayout android:layout_width="match_parent"
            android:id="@+id/linearLayout1"
            android:layout_height="match_parent">
<TextView android:id="@+id/textview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello" />
</LinearLayout> 
</ScrollView> 
</LinearLayout>

欢迎所有评论,希望我能在平均时间内弄清楚这一点。

警告:

以下行中的警告

--------------------
activity.java

import org.apache.http.NameValuePair;

List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("data1", "dataValue"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

---------------------
main xml

<ScrollView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/scrollView1">

<LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="match_parent">
----------------------

manifest

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

----------------------

2 个答案:

答案 0 :(得分:0)

我认为你遗失setDoInput( true )&amp;代码中的setDoOutput ( true )方法。

答案 1 :(得分:0)

错误似乎是由于行:

httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);

这些是无效的听众价值,您可以设置如下:

StringEntity se = new StringEntity( "JSON: " + json.toString());  
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);