android
最近在做毕业设计 放出一段 自己写的android下 使用多线程处理 向服务器请求数据 的代码 请大家多多指教啊!
废话少说啦 直接上代码:
/**
*
*/
package com.wary.odClient.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.wary.odClient.context.AppContext;
/**
* @author wary
* @create 2010-12-15 下午05:41:53
*
*/
public class MyHttpClient extends Thread
{
private String pathstr;
private List<NameValuePair> params;
private String result;
private boolean done;
/**
*
*/
public MyHttpClient(String pathstr,List<NameValuePair> params)
{
// TODO Auto-generated constructor stub
this.params = params;
this.pathstr = pathstr;
done = false;
}
public static String getResult(String pathstr,List<NameValuePair> params)
{
MyHttpClient httpClient = new MyHttpClient(pathstr, params);
long sTime = System.nanoTime();
httpClient.start();
while(true)
{
if((System.nanoTime() - sTime) > 5000000000l)
{
httpClient.interrupt();
httpClient.setResult("连接超时……");
httpClient.setDone(true);
break;
}else if(httpClient.isDone())
{
break;
}
}
return httpClient.getResult();
}
@Override
public void run()
{
// TODO Auto-generated method stub
super.run();
this.setResult(this.ResponseText());
while(result == null && !done)
{
this.setResult(this.ResponseText());
}
this.setDone(true);
}
public String ResponseText()
{
String responseText = null;
String urlStr = AppContext.serverPath + pathstr;
HttpPost httpRequest = new HttpPost(urlStr);
try
{
if( params != null)
httpRequest.setEntity(new UrlEncodedFormEntity(params ,HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
responseText = EntityUtils.toString(httpResponse.getEntity());
}else
{
System.out.println(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
return responseText;
}
/**
* @param result the result to set
*/
public void setResult(String result)
{
this.result = result;
}
/**
* @return the result
*/
public String getResult()
{
return result;
}
/**
* @param done the done to set
*/
public void setDone(boolean done)
{
this.done = done;
}
/**
* @return the done
*/
public boolean isDone()
{
return done;
}
}