最基本的HTTP请求方法是GET。在这种请求中,发送所有数据使用查询字符串嵌在URLk。
Socket:
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
HTTP:
url = new URL(location);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
in.close();
urlConn.disconnect();
Android以Apache httpClient库的形式提供了另一组API,这些API进一步的抽象了java.net类,提供了更健壮的HTTP支持并可帮助你处理单独线程问题。
HTTPCLIENT
private void performRequest() {
// use a response handler so we aren't blocking on the HTTP request
final ResponseHandler
responseHandler = new ResponseHandler
() {
public String handleResponse(HttpResponse response) {
// when the response happens close the notification and update UI
StatusLine status = response.getStatusLine();
Log.d(Constants.LOGTAG, " " + ApacheHTTPSimple.CLASSTAG + " statusCode - " + status.getStatusCode());
Log.d(Constants.LOGTAG, " " + ApacheHTTPSimple.CLASSTAG + " statusReasonPhrase - "
+ status.getReasonPhrase());
HttpEntity entity = response.getEntity();
String result = null;
try {
result = StringUtils.inputStreamToString(entity.getContent());
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("RESPONSE", result);
message.setData(bundle);
handler.sendMessage(message);
} catch (IOException e) {
Log.e(Constants.LOGTAG, " " + ApacheHTTPSimple.CLASSTAG, e);
}
return result;
}
};
this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");
// do the HTTP dance in a separate thread (the responseHandler will fire when complete)
new Thread() {
@Override
public void run() {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpMethod = new HttpGet(urlChooser.getSelectedItem().toString());
client.execute(httpMethod, responseHandler);
} catch (ClientProtocolException e) {
Log.e(Constants.LOGTAG, " " + ApacheHTTPSimple.CLASSTAG, e);
} catch (IOException e) {
Log.e(Constants.LOGTAG, " " + ApacheHTTPSimple.CLASSTAG, e);
}
}
}.start();
}
REST采用的主要概念是以URI的形式指定资源,然后使用不同的协议方法执行不同的操作。
private String parseXMLResult(String xmlString) {
StringBuilder result = new StringBuilder();
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
DeliciousHandler handler = new DeliciousHandler();
xr.setContentHandler(handler);
xr.parse(new InputSource(new StringReader(xmlString)));
List
posts = handler.getPosts();
for (DeliciousPost p : posts) {
Log.d(Constants.LOGTAG, " " + DeliciousRecentPosts.CLASSTAG + " DeliciousPost - " + p.getHref());
result.append("/n" + p.getHref());
}
} catch (Exception e) {
Log.e(Constants.LOGTAG, " " + DeliciousRecentPosts.CLASSTAG + " ERROR - " + e);
}
return result.toString();
}