2012-07-10 207 views
2

我想从AndroidHTTP POST请求的Android

联系的API

我发现这个示例代码...

public void postData() { 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 

} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 
} 

我的问题是,我怎么能看到,以确保它是响应得到一个?有没有添加API密钥的方法?

此外,“yoursite.com”必须是PHP文件吗?

+0

服务器不必在php中使用任何你想在服务器端。我们使用python和Django。 – sww314 2012-07-10 22:36:28

回答

4
HttpEntity entity = response.getEntity(); 
if (entity != null) { 
    InputStream instream = entity.getContent(); 
    try { 

     //read stream 
     //if expect binary data: 
     BufferedInputStream stream = new BufferedInputStream(instream); 
     int maxBytes = 128 * 1024; 
     if(entity.getContentLength() > maxBytes) { 
      throw new IllegalArgumentException("Much too big!"); 
     } 
     byte[] bytes = new byte[(int) entity.getContentLength()]; 
     int offset = 0, count = bytes.length; 
     while(stream.read(bytes, offset, count) > -1 && count > 0) { 
      count -= offset; 
     } 

     final Bitmap responseImage = BitmapFactory.decodeByteArray(
       bytes, 0, bytes.length); 

     //or if you expect text 
     BufferedReader reader = new BufferedReader(
       new InputStreamReader(instream, Charset.forName(
         entity.getContentEncoding().getValue()))); 

     StringBuffer buffer = new StringBuffer(); 
     String line; 
     while((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 

     final String responseText = buffer.toString(); 

    } finally { 
     instream.close(); 
    } 
} 
0

观看这些视频(YouTube Link)

它是制作登录应用程序为Android的6部分教程。它还显示了如何使用MySQL创建数据库。希望能帮助到你。