如何使用AndroidHttpClient
作爲HTTP客戶端連接到遠程服務器?我無法在文檔或互聯網上找到好的例子。如何在Android中使用簡單HTTP客戶端?
回答
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();
}
你的lmgtfy吸引了很多「攻擊性」的標誌。我強烈建議不要那樣做。 – 2010-12-16 09:37:32
明白了。下次我會盡量避免它。 – Cristian 2010-12-16 13:00:10
爲了使這個工作與GZIP,chunked流等,使用HttpClient和entity.writeTo()來代替。 – 2011-03-22 10:43:49
你可以使用這樣的:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}
您可以使用此代碼:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
歡迎來到Stack Overflow!感謝您發佈您的答案!請務必仔細閱讀[自助推廣常見問題](http://stackoverflow.com/faq#promotion)。另請注意,每次鏈接到您自己的網站/產品時,您都必須*發佈免責聲明。 – 2013-03-15 03:48:32
- 1. 簡單的C++異步http客戶端
- 2. 如何在Android中實現簡單的聊天客戶端?
- 3. 如何使用HTTP客戶端傳遞客戶端證書?
- 4. 如何使用HTTP客戶端
- 5. 異步HTTP客戶端 - 如何使用
- 6. 簡單的Android套接字客戶端
- 7. 在akka-http客戶端中使用PlayJson
- 8. 在HTTP客戶端中使用WebViews cookie
- 9. 如何使用icecast客戶端在android
- 10. 如何在android中使ssh客戶端
- 11. 如何在Android應用中緩存Http客戶端的響應?
- 12. 使用Http客戶端
- 13. Android異步Http客戶端
- 14. Android LoopJ的HTTP客戶端
- 15. Android HTTP客戶端死機
- 16. Android Defaul Http客戶端
- 17. Android上的HTTP客戶端
- 18. Android HTTP客戶端問題
- 19. 在HTTP客戶端
- 20. 簡單的JMX客戶端
- 21. Java:簡單SOAP客戶端
- 22. 在Android Studio中使用Google HTTP客戶端
- 23. 在Android應用中使用http客戶端模擬表單發佈?
- 24. 構建簡單的HTTP客戶端在C
- 25. 如何使用JBuddy SDK創建簡單的yahoo messenger客戶端?
- 26. 如何在Delphi中使用HTTP客戶端API xe
- 27. 如何在Akka-http(客戶端)HttpRequest中使用.withoutSizeLimit?
- 28. 如何使用來自Android客戶端
- 29. Python中的簡單SOAP客戶端
- 30. 使用HTTP客戶端的Java 4.5客戶端獲取語句
這實際上是一個非常有用的問題。沒有很多關於如何使用AndroidHttpClient的例子。也許這個問題應該更具體。 – 2013-08-03 19:24:17
我更新了這個以使其成爲一個真正的問題。請重新打開它,因爲如你所見,這對很多人來說都是一個有用的問題。 – 2014-04-10 21:19:06
我們要重新打開這個還是什麼? – 2014-04-10 21:22:34