2012-01-20 3 views
0

Я пытаюсь получить метод пост получить в андроид приложение, но некоторые, как я получаю ошибкиандроида сообщение об ошибке HTTP приложение

Беллоу основные файлы, используемые в приложении.

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> 

---------------------- 
+0

Вы уплетая исключение даже не их регистрации, прежде чем делать это, и там это не журнал или описание вашей ошибки. Пожалуйста, предоставьте некоторые детали ошибки, если вам нужна помощь. – Anirudh

+1

Какая ошибка –

ответ

0

Ошибка кажется из-за линии:

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

это не действительное значение hearder, вы можете установить, как показано ниже:

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

Я думает, что вам не хватает setDoInput(true) & setDoOutput (true) методы в вашем коде ,

+0

? можете ли вы объяснить больше – arjun

+0

, вам нужно использовать эти методы при отправке/получении данных с использованием метода POST. – Lucifer

Смежные вопросы