【发布时间】:2014-08-04 13:33:06
【问题描述】:
我已经实现了 AsyncTask 来向 webService 发出 http 请求,但是当我尝试获取服务器返回的编译器字符串时它给了我一个错误。
这是我认为 AsyncTask 的活动代码:
public String consultaPreguntaBBDD(int num, String tab)
{
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(String.valueOf(num),tab);
/*(!)*/String resul = httpAsyncTask.execute("http://appdomain.hol.es/webService.php");
return resul;
}
我写这个(!)的地方编译器说:类型不匹配:无法从 AsyncTask 转换为字符串 这是 AsyncTask 类:
class HttpAsyncTask extends AsyncTask<String, Void, String>
{
private static String id;
private static String te;
public HttpAsyncTask(String id,String te)
{
this.id = id;
this.te = te;
}
@Override
protected String doInBackground(String... urls)
{
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
}
public static String POST(String url)
{
InputStream inputStream = null;
String result = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
// pass parameters in this way
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", id));
nameValuePairs.add(new BasicNameValuePair("te", te));
//add data
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e)
{
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
Log.i("http","result: "+result+"\n");
return result;
}
}
我有两个文件,每个班级一个 谁能帮我?谢谢
【问题讨论】:
-
@jaimin 我复制了帖子以便更好地查看问题
-
在stackoverflow中你不能再次发布同样的问题/怀疑,否则你会被否决
-
@jaimain 对不起,我不知道
标签: android http android-asynctask