如何在Android中使用简单的HTTP客户端?
如何使用如何在Android中使用简单的HTTP客户端?,android,http,Android,Http,如何使用AndroidHttpClient作为HTTP客户端连接到远程服务器?我无法在文档或互联网上找到好的示例。您可以这样使用: public static void connect(String url) { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object HttpGet httpget = new HttpGet(url); // Execute
AndroidHttpClient
作为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();
}
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;
}
public静态字符串executeHttpPost1(字符串url,
HashMap后参数)引发不支持的DencodingException{
//TODO自动生成的方法存根
HttpClient=getNewHttpClient();
试一试{
请求=新的HttpPost(url);
}
捕获(例外e){
e、 printStackTrace();
}
if(postParameters!=null&&postParameters.isEmpty()==false){
List nameValuePairs=新的ArrayList(postParameters.size());
串k,v;
迭代器itKeys=postParameters.keySet().Iterator();
while(itKeys.hasNext())
{
k=itKeys.next();
v=后参数get(k);
添加(新的BasicNameValuePair(k,v));
}
UrlEncodedFormEntity UrleEntity=新的UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
试一试{
Response=client.execute(请求、本地上下文);
HttpEntity=Response.getEntity();
int statusCode=Response.getStatusLine().getStatusCode();
Log.i(标记“+”状态代码);
Log.i(标记“------------------------------------------------------------”);
试一试{
InputStream in=(InputStream)entity.getContent();
//Header contentEncoding=Response.getFirstHeader(“内容编码”);
/*if(contentEncoding!=null&&contentEncoding.getValue().equalsIgnoreCase(“gzip”)){
in=新的GZIPInputStream(in);
}*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
StringBuilder str=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
str.append(第+行“\n”);
}
in.close();
response=str.toString();
Log.i(标签,“响应”+响应);
}
捕获(非法状态异常exc){
exc.printStackTrace();
}
}捕获(例外e){
Log.e(“Log_标记”,“http连接错误”+响应);
}
最后{
}
返回响应;
}
您可以使用以下代码:
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());
}
你的lmgtfy吸引了很多“进攻性”旗帜。我强烈建议不要那样做,明白了。下次我会尽量避免它。要使GZIP、分块流等工作正常,请改用HttpClient和entity.writeTo()。如果不使用HttpClient,蜂巢和更新版本将抛出
NetworkOnMainThreadException
。HttpClient现在是一个遗留问题。您最好使用OkHttp,因为Android SDK 23棉花糖。欢迎使用堆栈溢出!谢谢你的回复!请务必仔细阅读本手册。还请注意,每次链接到自己的网站/产品时,都需要发布免责声明。这实际上是一个有用的问题。关于如何使用AndroidHttpClient的例子并不多。也许这个问题应该更具体一些。我更新了这个,使它成为一个真正的问题。请重新打开它,因为正如你所看到的,这对很多人来说是一个有用的问题。我们是要重新打开这个还是什么?为什么?这对我来说毫无意义。有时我完全困惑和沮丧。我通过谷歌安卓http客户端示例到达这里。似乎高于平均水平的程序员的问题是真实的。