2010-02-24 15 views
46

मैं एक एचटीपीपोस्ट अनुरोध भेजने और प्रतिक्रिया प्राप्त करने के लिए लंबे समय से प्रयास कर रहा हूं लेकिन भले ही मैं कनेक्शन बनाने में सक्षम था, फिर भी मुझे यह नहीं मिला कि स्ट्रिंग संदेश कैसे प्राप्त किया जाए अनुरोध-प्रतिक्रियाएंड्रॉइड एचटीपीपोस्ट: परिणाम कैसे प्राप्त करें

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php"); 
// Add your data 
List <NameValuePair> nameValuePairs = new ArrayList <NameValuePair> (5); 
nameValuePairs.add(new BasicNameValuePair("type", "20")); 
nameValuePairs.add(new BasicNameValuePair("mob", "919895865899")); 
nameValuePairs.add(new BasicNameValuePair("pack", "0")); 
nameValuePairs.add(new BasicNameValuePair("exchk", "1")); 

try { 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    Log.d("myapp", "works till here. 2"); 
    try { 
     HttpResponse response = httpclient.execute(httppost); 
     Log.d("myapp", "response " + response.getEntity()); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} catch (UnsupportedEncodingException e) { 
    e.printStackTrace(); 
} 

मुझे खेद है, मैं बहुत मूर्ख हूं क्योंकि मैं जावा के लिए नया हूं। क्रिप्या मेरि सहायता करे।

+0

हाय, मैं इस पोस्ट में आया, और मैं सोच रहा था कि क्या आप मुझे बता सकते हैं कि आपका ऐरेलिस्ट क्यों है (5) और नहीं (4)? – hellomello

+0

मैंने इसे पोस्ट करने से पहले एक पैरा हटा दिया और सरणी सूची को बदलना भूल गया। –

+2

"एचटीपी क्लाइंट", "एचटीपीपोस्ट", "एचटीपीपीस्पॉन्स", "एचटीपीएन्टीटी", "एंटीटीयूट्स", "नेमवैल्यूपेयर", "बेसिकनाम वैल्यूपेयर" बहिष्कृत हैं। कृपया एक और समाधान का सुझाव दें। –

उत्तर

96

कोशिश आपकी प्रतिक्रिया पर EntityUtil उपयोग करने के लिए:

String responseBody = EntityUtils.toString(response.getEntity()); 
+0

हाय सोलेरेपर, आपकी प्रतिक्रिया के लिए धन्यवाद। लेकिन EntityUtil का उपयोग क्यों किया जाता है? –

+0

यह स्ट्रिंग फॉर्म में निहित कच्चे बाइट उत्तर निकालने का एक सुविधाजनक तरीका है। – Moritz

+0

धन्यवाद @ मॉरित्ज़ – Hamid

7
URL url; 
    url = new URL("http://www.url.com/app.php"); 
    URLConnection connection; 
    connection = url.openConnection(); 
    HttpURLConnection httppost = (HttpURLConnection) connection; 
    httppost.setDoInput(true); 
    httppost.setDoOutput(true); 
    httppost.setRequestMethod("POST"); 
    httppost.setRequestProperty("User-Agent", "Tranz-Version-t1.914"); 
    httppost.setRequestProperty("Accept_Language", "en-US"); 
    httppost.setRequestProperty("Content-Type", 
      "application/x-www-form-urlencoded"); 
    DataOutputStream dos = new DataOutputStream(httppost.getOutputStream()); 
    dos.write(b); // bytes[] b of post data 

    String reply; 
    InputStream in = httppost.getInputStream(); 
    StringBuffer sb = new StringBuffer(); 
    try { 
     int chr; 
     while ((chr = in.read()) != -1) { 
      sb.append((char) chr); 
     } 
     reply = sb.toString(); 
    } finally { 
     in.close(); 
    } 

यह कोड स्निपेट काम करता है। मुझे खोज के साथ मिल गया, लेकिन एक जे 2 एमई कोड से।

+0

आपने यूआरएल के साथ भेजे जाने वाले मानों को कहाँ जोड़ा? – zaiff

+0

httppost.setRequestProperty ("पैरामीटर_variable_name", मान) - मुझे लगता है कि यह काम करेगा। क्षमा करें थोड़ी देर के बाद से मैंने कुछ भी ऐसा करने की कोशिश की है। अच्छी तरह से याद नहीं कर सका। –

+0

बस यह कह रहा है कि यह स्निपसेट पुरानी है और httpost अनुरोधों को चलाने का एक और तरीका है। – Fattum

7

आप एक ResponseHandler साथ विधि पर अमल कॉल कर सकते हैं। यहां एक उदाहरण दिया गया है:

ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
String response = httpClient.execute(httppost, responseHandler); 
+1

हाय सर, आपकी प्रतिक्रिया के लिए धन्यवाद। लेकिन, इसका उपयोग करने का क्या फायदा है? –

1

इसे आजमाएं, ऐसा लगता है कि यह सबसे कॉम्पैक्ट है। यद्यपि असली दुनिया में, आपको एक एसिंक्रोनस अनुरोध का उपयोग करना होगा, इसलिए अनुरोध किया गया पृष्ठ पुनर्प्राप्त होने पर डिवाइस लटका नहीं होगा।

http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/

4

आप इस तरह से

public class MyHttpPostProjectActivity extends Activity implements OnClickListener { 

private EditText usernameEditText; 
private EditText passwordEditText; 
private Button sendPostReqButton; 
private Button clearButton; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 

    usernameEditText = (EditText) findViewById(R.id.login_username_editText); 
    passwordEditText = (EditText) findViewById(R.id.login_password_editText); 

    sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button); 
    sendPostReqButton.setOnClickListener(this); 

    clearButton = (Button) findViewById(R.id.login_clear_button); 
    clearButton.setOnClickListener(this);   
} 

@Override 
public void onClick(View v) { 

    if(v.getId() == R.id.login_clear_button){ 
     usernameEditText.setText(""); 
     passwordEditText.setText(""); 
     passwordEditText.setCursorVisible(false); 
     passwordEditText.setFocusable(false); 
     usernameEditText.setCursorVisible(true); 
     passwordEditText.setFocusable(true); 
    }else if(v.getId() == R.id.login_sendPostReq_button){ 
     String givenUsername = usernameEditText.getEditableText().toString(); 
     String givenPassword = passwordEditText.getEditableText().toString(); 

     System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword); 

     sendPostRequest(givenUsername, givenPassword); 
    } 
} 

private void sendPostRequest(String givenUsername, String givenPassword) { 

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{ 

     @Override 
     protected String doInBackground(String... params) { 

      String paramUsername = params[0]; 
      String paramPassword = params[1]; 

      System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword); 

      HttpClient httpClient = new DefaultHttpClient(); 

      // In a POST request, we don't pass the values in the URL. 
      //Therefore we use only the web page URL as the parameter of the HttpPost argument 
      HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php"); 

      // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be 
      //uniquely separate by the other end. 
      //To achieve that we use BasicNameValuePair    
      //Things we need to pass with the POST request 
      BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername); 
      BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword); 

      // We add the content that we want to pass with the POST request to as name-value pairs 
      //Now we put those sending details to an ArrayList with type safe of NameValuePair 
      List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); 
      nameValuePairList.add(usernameBasicNameValuePair); 
      nameValuePairList.add(passwordBasicNameValuePAir); 

      try { 
       // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
       //This is typically useful while sending an HTTP POST request. 
       UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList); 

       // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request. 
       httpPost.setEntity(urlEncodedFormEntity); 

       try { 
        // HttpResponse is an interface just like HttpPost. 
        //Therefore we can't initialize them 
        HttpResponse httpResponse = httpClient.execute(httpPost); 

        // According to the JAVA API, InputStream constructor do nothing. 
        //So we can't initialize InputStream although it is not an interface 
        InputStream inputStream = httpResponse.getEntity().getContent(); 

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 

        StringBuilder stringBuilder = new StringBuilder(); 

        String bufferedStrChunk = null; 

        while((bufferedStrChunk = bufferedReader.readLine()) != null){ 
         stringBuilder.append(bufferedStrChunk); 
        } 

        return stringBuilder.toString(); 

       } catch (ClientProtocolException cpe) { 
        System.out.println("First Exception caz of HttpResponese :" + cpe); 
        cpe.printStackTrace(); 
       } catch (IOException ioe) { 
        System.out.println("Second Exception caz of HttpResponse :" + ioe); 
        ioe.printStackTrace(); 
       } 

      } catch (UnsupportedEncodingException uee) { 
       System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee); 
       uee.printStackTrace(); 
      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      if(result.equals("working")){ 
       Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show(); 
      }else{ 
       Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show(); 
      } 
     }   
    } 

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(); 
    sendPostReqAsyncTask.execute(givenUsername, givenPassword);  
} 

}

+0

हाय सिद्धपुरा, क्या आप एक ही समय में लिख रहे हैं और पढ़ रहे हैं? सिर्फ जानकारी भेजने के लिए मुझे क्या करना चाहिए? मैं आपके जैसा करने की कोशिश करता हूं लेकिन यह मेरे लिए काम नहीं करता है। POST विधि के साथ डेटा भेजने के लिए यह वास्तव में क्या हिस्सा है? धन्यवाद! –

+0

@ सिद्धपुरा: पैरामीटर के नाम के लिए मुझे क्या मूल्य रखना चाहिए? मेरा मतलब है कि इसका "आईडी" इसका नाम "नाम" है? क्रिप्या मेरि सहायता करे। धन्यवाद। – karimkhan

0

इसके बजाय आप HttpPost की HttpGet का उपयोग कर प्रयास करना चाहिए ऐसा कर सकते हैं। मुझे एक ही समस्या थी और इसे हल किया।

संबंधित मुद्दे