Java HttpPost每5秒响应一次
我试图从服务器读取一个变量,每5秒对其求值一次,然后发送另一个变量,但我无法将此代码转换为该变量。并尝试使用计时器,但这不起作用,而且我不太了解SoTimeout,无法以这种方式使用它[。]我希望接收到的变量只能通过某些条件进行计算。[一] 我是这个httppost的新手Java HttpPost每5秒响应一次,java,android,timeout,http-post,Java,Android,Timeout,Http Post,我试图从服务器读取一个变量,每5秒对其求值一次,然后发送另一个变量,但我无法将此代码转换为该变量。并尝试使用计时器,但这不起作用,而且我不太了解SoTimeout,无法以这种方式使用它[。]我希望接收到的变量只能通过某些条件进行计算。[一] 我是这个httppost的新手 private void EnviarDatos(int var){ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppos
private void EnviarDatos(int var){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.******.com/leo/app2.php");
try {
List<NameValuePair> postValues = new ArrayList<NameValuePair>(2);
postValues.add(new BasicNameValuePair("a", Integer . toString ( var )));
httppost.setEntity(new UrlEncodedFormEntity(postValues));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String res= StreamToString(is);
int entero = Integer.parseInt(res);
Message sms = new Message();
sms.obj = res;
bridge.sendMessage(sms);
}catch (IOException e) {
//TODO Auto-generated catch block
}
}
public String StreamToString(InputStream is) {
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();
}
private Handler bridge = new Handler() {
@Override
Toast.makeText(getApplicationContext(), (String)msg.obj,
Toast.LENGTH_LONG).show();
}
};
private void envirardatos(int-var){
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.******com/leo/app2.php);
试试{
List postValues=新的ArrayList(2);
add(新的BasicNameValuePair(“a”,Integer.toString(var));
setEntity(新的UrlEncodedFormEntity(postValues));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
InputStream=entity.getContent();
String res=StreamToString(is);
int entero=整数.parseInt(res);
消息sms=新消息();
sms.obj=res;
桥接发送消息(sms);
}捕获(IOE){
//TODO自动生成的捕捉块
}
}
公共字符串StreamToString(InputStream为){
BufferedReader读取器=
新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
私有处理程序桥=新处理程序(){
@凌驾
Toast.makeText(getApplicationContext(),(String)msg.obj,
Toast.LENGTH_LONG).show();
}
};
设置otimeout用于指定您希望等待服务器响应的时间,因此您可以将其设置为等待10秒,之后将继续此过程,我建议您为此任务创建服务。这是一个非常完整的教程:
试试这个:
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// What you want to do goes here
}
}, 0, REFRESH_TIME);
针对您的问题,有几种解决方案:
你需要用英语重新编写你的问题。如果你第一次发帖,但在一个连续的周期内出错,那么问题就可以解决了