【问题标题】:Call Async a Restfull WebService in Android Java在 Android Java 中调用异步一个 Restful WebService
【发布时间】:2016-11-07 08:13:45
【问题描述】:

我需要调用 android java 中的 web 服务,然后另一个类调用它。我结束了,在 UI 中显示 ws 响应。

我已经完成了网络服务。只有“异步”的那一部分不能正常工作。

这是我的网络服务,接收三个字符串:

public class WebServiceRestFull extends AsyncTask<String, String, String>
{
    protected ProgressDialog dialog;


    public String wsURL;
    public String wsFunction;
    public String wsInput;

    public int codeHTTP;
    public String messageHTTP;
    public String strResponse;


    public WebServiceRestFull(Context act)
    {
        dialog = new ProgressDialog(act);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Wait please...");
        dialog.show();
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (dialog.isShowing())
        {
            dialog.dismiss();
        }
    }

    @Override
    protected String doInBackground(String... params)
    {
String url = wsURL + wsFunction;
        String inputCoded = EncodeString(wsInput);

        HttpURLConnection request;

        URL urlToRequest = new URL(url);
        request = (HttpURLConnection) urlToRequest.openConnection();

        request.setDoOutput(true);
        request.setDoInput(true);
        request.setRequestProperty("Content-Type", "application/json");
        request.setRequestMethod("POST");

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(request.getOutputStream());
        outputStreamWriter.write("\""+inputCoded+"\"");
        outputStreamWriter.flush();
        outputStreamWriter.close();

        codeHTTP = request.getResponseCode();
        messageHTTP = request.getResponseMessage();

        InputStream is = request.getInputStream();

        String resp = convertStreamToString(is);
        strResponse = DecodeString(resp);

        request.disconnect();

       
        return strResponse;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        return "ERROR";
    }
    }      
}

另一方面,在“Android Activity”中,我将这个异步类调用如下:

WebServiceRestFull web = new WebServiceRestFull(this);
web.wsURL = "http://someurl.com/rest/etc";
web.wsFunction = "login";
web.wsInput = "mike";
web.execute();
Thread.sleep(1000);

问题在于,这实际上并没有进行异步调用,而且结果通常不会被 web 服务接收到。

有什么简单的方法可以做到这一点,还是我在调用 web 服务或自己的 web 服务类时做错了?

对不起我的英语。

谢谢!

【问题讨论】:

  • 你为什么使用 Thread.sleep(1000) ?而是使用回调方法来获取结果之后的结果。

标签: java android web-services


【解决方案1】:

您创建和执行此异步任务的方式没有问题

请不要使用 Thread.sleep();

问题显然出在 doInBackground() 方法中,我们这里没有哪些代码

【讨论】:

  • 尝试查看日志,如果在请求过程中出现问题,应该会有一些警告
【解决方案2】:

您的代码是否完整?你的课堂上没有任何东西可以发出 http 请求,其余的似乎都很好。 尝试使用 Okhttp 真的很简单。检查它here

该线程睡眠将在主线程中运行,这不是一个好主意。使用 post execute 运行您的回调并发布任何结果。

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2013-01-28
    • 2015-04-30
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多