本文介绍了我如何使用简单的HTTP客户端在Android中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用 AndroidHttpClient
作为HTTP客户端连接到远程服务器?我一直没能找到的文件,也没有在互联网上很好的例子。
解决方案
公共静态无效连接(字符串URL)
{
HttpClient的HttpClient的=新DefaultHttpClient();
// prepare请求对象
HTTPGET HTTPGET =新HTTPGET(URL);
//执行请求
HTT presponse响应;
尝试 {
响应= httpclient.execute(HTTPGET);
//检查响应状态
Log.i(Praeda,response.getStatusLine()的toString());
//弄个响应实体
HttpEntity实体= response.getEntity();
//如果响应不围绕的实体,也没有必要
//担心连接释放
如果(实体!= NULL){
//一个简单的JSON响应读取
InputStream的河道= entity.getContent();
字符串结果= convertStreamToString(河道);
//现在你有串重的HTML请求presentation
instream.close();
}
}赶上(例外五){}
}
私有静态字符串convertStreamToString(InputStream的是){
/ *
*要InputStream中转换为字符串,我们使用使用BufferedReader.readLine()
* 方法。我们迭代直到BufferedReader中返回NULL,这意味着
*没有更多的数据读取。每个行会附加到一个StringBuilder
*和返回的字符串。
* /
的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(是));
StringBuilder的SB =新的StringBuilder();
串线= NULL;
尝试 {
而((行= reader.readLine())!= NULL){
sb.append(行+\ N);
}
}赶上(IOException异常E){
e.printStackTrace();
} 最后 {
尝试 {
is.close();
}赶上(IOException异常E){
e.printStackTrace();
}
}
返回sb.toString();
}
How do I use the AndroidHttpClient
as an HTTP client to connect to a remote server? I have not been able to find good examples in the documentation nor on the internet.
解决方案
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
这篇关于我如何使用简单的HTTP客户端在Android中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!