2012-04-07 74 views
0

我找到了this使用http的PostData主題。但它不起作用。如何在Android中發佈數據?

怎麼了?

我還要求在manifestAndroid.permission.INTERNET

public void postData() { 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http:/mysite.com/postTest.php"); 
    try { 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
     nameValuePairs.add(new BasicNameValuePair("pw", "12456")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 
     tv.setText(response.toString()); 
    } catch (ClientProtocolException e) { 
     // 
    } catch (IOException e) { 
     // 
    } 
} 

編輯

我的應用程序將使用此消息被終止: Unfortunately PostDataProject has stopped.

+1

「沒有關係沒有工作「 - 沒有例外,沒有描述,也不知道問題出在哪裏。 – 2012-04-07 10:17:54

+0

你如何知道它不工作? – 2012-04-07 10:19:49

+0

我的問題被編輯。謝謝 – Kermia 2012-04-07 10:21:04

回答

2

試試這個:

HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = responce.getEntity(); 
// convert stream to String 
BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent())); 
StringBuilder sb1 = new StringBuilder(); 
String line = null; 
while ((line = buf.readLine()) != null) { 
sb1.append(line); 
} 
tv.setText(sb1.toString()); 

和u可以照片直接設置爲TextView的,如果數據僅供textvew或小:

tv.setText(EntityUtils.toString(response.getEntity())); 

,並使用此:

HttpPost httppost = new HttpPost("http://mysite.com/postTest.php"); 

代替

HttpPost httppost = new HttpPost("http:/mysite.com/postTest.php"); 
+0

我追溯了代碼。該錯誤在這一行中發生:'HttpResponse response = httpclient.execute(httppost)';' – Kermia 2012-04-07 10:28:38

+2

你缺少// http:/ – 2012-04-07 10:29:40

+0

OMG! :|謝謝 – Kermia 2012-04-07 10:31:02