2012-04-20 63 views
0

我在Android上提出了一个问题,但没有得到任何答案,但我在iPhone平台上找到了类似的问题,但我不知道如何将其转换为Java代码。请任何熟悉两种语言的人都可以试试看。将iPhone代码转换为Android

NSString* userAgent = @"Mozilla/5.0"; 

NSURL *url = [NSURL URLWithString:[@"http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα" 
         stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; 

[request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; 

NSURLResponse* response = nil; 
NSError* error = nil; 
NSData* data = [NSURLConnection sendSynchronousRequest:request 
           returningResponse:&response 
              error:&error]; 


[data writeToFile:@"/var/tmp/tts.mp3" atomically:YES]; 
+0

这是可能的,生病尝试有一个裂缝呢? – FabianCook 2012-04-20 12:10:41

+2

你想我把一些代码从'iPhone'转换成'Android',是吗?我的费率非常有竞争力。给我打个电话。 – 2012-04-20 12:11:16

+0

他正在尝试使用http获取该链接的响应。 – FabianCook 2012-04-20 12:13:26

回答

0
HttpClient httpclient = new DefaultHttpClient(); 

HttpGet httpget = new HttpGet("http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα"); 

HttpResponse response = httpclient.execute(httpget); 

然后得到的一些文件从响应怎么会在这里?对不起我没有IDE。

也许这样?

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = factory.newDocumentBuilder(); 
Document doc = builder.parse(response.getEntity().getContent()); 

我不知道如何解析mp3文件tho?

什么像

InputStream is = response.getEnitity().getContent(); 
BufferedInputStream bis = new BufferedInputStream(is); 
ByteArrayBuffer baf = new ByteArrayBuffer(50); 
int current = 0; 
while ((current = bis.read()) != -1) { 
    baf.append((byte) current); 
} 

FileOutputStream fos = new FileOutputStream(file); 
fos.write(baf.toByteArray()); 
fos.close(); 
1

好吧,我想通了,(据我所知)

他正试图下载文件格式的Web和我电话它保存到本地存储,

在Android中尝试这个代码,

try { 
     URL url = new URL("http://www.translate.google.com/translate_tts?tl=el&q=Καλημέρα"); 
     URLConnection connection = url.openConnection(); 
     connection.connect(); 
     // this will be useful so that you can show a typical 0-100% progress bar 
     int fileLength = connection.getContentLength(); 

     // download the file 
     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream("/sdcard/tts.mp3"); 

     byte data[] = new byte[1024]; 
     int count; 
     while ((count = input.read(data)) != -1) { 
      output.write(data, 0, count); 
     } 
     output.flush(); 
     output.close(); 
     input.close(); 
    } catch (Exception e) { 
    } 

还别说使用许可权的哟你的Android Manifest.xml文件像,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

现在,这将存储您下载的MP3文件在外部存储。

+0

它是否说过更改useragent? – Amanni 2012-04-20 13:10:58

+0

不,上面的代码中没有任何用户代理需要android .. – user370305 2012-04-21 05:03:10