2010-12-05 15 views
5

Bir http sunucusuna bir istek göndermek için bu kodu kullanıyorum:Okuma HttpPost tepkisi

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://192.168.0.1/test.php"); 
HttpResponse response = null; 
try { 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("num", "2")); 
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    response = client.execute(post); 
} 
catch(ClientProtocolException e) { 
    ... 
} 
catch(IOException e) { 
    ... 
} 

yanıtı basit String başka bir şey değildir. Bu yanıtı String olarak nasıl okuyabilirim? HttpResponse'nin bunu doğrudan yapmak için bir yöntemi var gibi görünmüyor.

Ben (eğer herhangi bir özel başlıkları yoksa boş olabilir HashMap başlıklarını) Android'de POST yöntemiyle veri ve özel başlıkları göndermek için bu yardımcı yöntemini oluşturduk

cevap

10

: durumunu okuma için

public static String getStringContent(String uri, String postData, 
     HashMap<String, String> headers) throws Exception { 

     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(); 
     request.setURI(new URI(uri)); 
     request.setEntity(new StringEntity(postData)); 
     for(Entry<String, String> s : headers.entrySet()) 
     { 
      request.setHeader(s.getKey(), s.getValue()); 
     } 
     HttpResponse response = client.execute(request); 

     InputStream ips = response.getEntity().getContent(); 
     BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8")); 
     if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK) 
     { 
      throw new Exception(response.getStatusLine().getReasonPhrase()); 
     } 
     StringBuilder sb = new StringBuilder(); 
     String s; 
     while(true) 
     { 
      s = buf.readLine(); 
      if(s==null || s.length()==0) 
       break; 
      sb.append(s); 

     } 
     buf.close(); 
     ips.close(); 
     return sb.toString(); 

} 
+1

IMHO kontrol etmek daha iyidir, eğer durum Tamam ilk (response.getStatusLine(). getStatusCode() == HttpStatus.SC_OK) {// bazı kod} else {// bazı ele ..} –

+0

eğer Bunu try-catch bloğu ile kapatmayı unutmayın;) – Taner

+0

th Yanıtın dizgisi milyon/milyar karaktere sahipse, etkili bir şekilde etkili değildir. Çok yavaş. Test ettim –

5

response.getStatusLine(); // satır

org.apache.http.util.EntityUtils.toString(response.getEntity());