簡體   English   中英

如何從遠程服務器加載一些文本?

[英]how to load some text from remote server?

我只是想知道是否可以在Android中從網絡加載一些文本。 如果是這樣,請給我一些示例代碼。 提前致謝!

當然,你可以使用GET或POST

 public static String makeGETRequest(String s,String encoding)
{   
    DefaultHttpClient http = new DefaultHttpClient();
    HttpResponse res;
    try {

        res = http.execute(new HttpGet(s));
        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }

        return  new String(baf.toByteArray(),encoding);
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return "error: " + e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return "error: " + e.getMessage();
    } 

}

帖子:

public static String makePOSTRequest(String s, List <NameValuePair> nvps,String encoding)
{

    DefaultHttpClient http = new DefaultHttpClient();


    HttpResponse res;
    try {
        HttpPost httpost = new HttpPost(s);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));

        res = http.execute(httpost);


        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        res = null;
        httpost = null;
        String ret = new String(baf.toByteArray(),encoding);
        return  ret;
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 

}

您可以使用HttpClient 這里有一個例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM