how to load some text from remote server?
I am just wondering if it is possible to load some text from the web in Android. If so, please can you give me some sample code. Thanks in advance!
sure, you can use GET or 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();
}
}
Post:
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();
}
}
You can use HttpClient. An example is available here.
精彩评论