如何在Android中使用DefaultHttpClient?
答案 0 :(得分:15)
我建议阅读android-api提供的教程。
这是一个使用DefaultHttpClient的随机示例,通过examples-folder中的简单文本搜索找到。
编辑:样本来源并不打算显示某些内容。它只是请求了url的内容并将其存储为字符串。下面是一个显示它加载内容的示例(只要它是字符串数据,如html-,css-或javascript-文件):
<强> main.xml中强>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
在你的应用的onCreate中添加:
// Create client and set our specific user-agent string
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://stackoverflow.com/opensearch.xml");
request.setHeader("User-Agent", "set your desired User-Agent");
try {
HttpResponse response = client.execute(request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
// Pull content stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
// Return result from buffered stream
String dataAsString = new String(content.toByteArray());
TextView tv;
tv = (TextView) findViewById(R.id.textview);
tv.setText(dataAsString);
} catch (IOException e) {
Log.d("error", e.getLocalizedMessage());
}
此示例现在加载给定URL的内容(示例中为stackoverflow的OpenSearchDescription),并将接收到的数据写入TextView。
答案 1 :(得分:3)
以下是一般代码示例:
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI("http://foo.com"));
HttpResponse response = defaultHttpClient.execute(method);
InputStream data = response.getEntity().getContent();
//Now we use the input stream remember to close it ....
答案 2 :(得分:0)
public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)
从参数和连接管理器创建新的HTTP客户端。
参数
"conman"
连接管理器,
"params"
参数
public DefaultHttpClient (HttpParams params)
public DefaultHttpClient ()