2010-02-24 36 views
46

Tôi đã cố gắng gửi yêu cầu HttpPost dài và truy xuất phản hồi nhưng mặc dù tôi có thể tạo kết nối nhưng tôi chưa nhận được thông báo chuỗi được trả về yêu cầu trả lờiAndroid HttpPost: cách lấy kết quả

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

Xin lỗi, tôi rất ngây thơ vì tôi mới sử dụng java. Làm ơn giúp tôi.

+0

Xin chào, tôi đã xem qua bài đăng này và tôi đã tự hỏi liệu bạn có thể cho tôi biết tại sao ArrayList của bạn là (5) chứ không phải (4)? – hellomello

+0

Tôi đã xóa một Params trước khi đăng nó ở đây và chỉ quên thay đổi danh sách mảng. –

+2

"HttpClient", "HttpPost", "HttpResponse", "HttpEntity", "EntityUtils", "NameValuePair", "BasicNameValuePair" không được chấp nhận. Vui lòng đề xuất giải pháp khác. –

Trả lời

96

Cố gắng sử dụng EntityUtil trên trả lời của bạn:

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

Hi Soulreaper, Cảm ơn bạn đã trả lời. Nhưng tại sao EntityUtils lại được sử dụng? –

+0

Đây chỉ là một cách thuận tiện để trích xuất câu trả lời byte thô chứa thành dạng chuỗi. – Moritz

+0

Cảm ơn bạn @Moritz – 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(); 
    } 

Đoạn mã này hoạt động. Tôi nhận được nó sau khi tìm kiếm, nhưng từ mã J2ME.

+0

bạn đã thêm các giá trị được gửi cùng url ở đâu? – zaiff

+0

httppost.setRequestProperty ("parameter_variable_name", giá trị) - Tôi đoán điều này sẽ làm việc. Xin lỗi đã được một thời gian tôi đã thử bất cứ điều gì tương tự. Không thể hồi tưởng tốt. –

+0

Chỉ cần nói, rằng snipset này đã lỗi thời cho các độ tuổi và có một cách khác để chạy các yêu cầu httpost. – Fattum

7

Bạn có thể gọi thực hiện phương pháp với một ResponseHandler. Dưới đây là ví dụ:

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

Xin chào Sarp, Cảm ơn bạn đã trả lời. Nhưng, lợi thế của việc sử dụng này là gì? –

4

Bạn có thể làm điều này bằng cách này

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

Hi Siddhpura, bạn đang viết và đọc cùng một lúc? Tôi nên làm gì để gửi thông tin? Tôi cố gắng làm như bạn nhưng nó không hiệu quả với tôi. Phần nào chính xác để gửi dữ liệu bằng phương thức POST? Cảm ơn bạn! –

+0

@Siddhpura: giá trị nào tôi phải đặt cho tên tham số? tôi có nghĩa là nó "id" của các tham số của nó là "tên"? làm ơn giúp tôi. cảm ơn. – karimkhan

0

Bạn nên cố gắng sử dụng HttpGet thay vì HttpPost. Tôi đã có một vấn đề tương tự và giải quyết nó.

Các vấn đề liên quan