Async HttpRequest Timing Out

时间:2017-11-03 17:14:06

标签: android android-asynctask request

问题

我有一个从Activity的OnCreate方法调用的AsyncTask任务。此任务发出http请求。 HTTP请求挂起。一旦" CODE HANGS HERE"执行下面代码中的代码,我在调试器中观察到异步线程永远都在运行'并且永远不会返回任何东西。

守则

这是活动的OnCreate方法:

protected void onCreate(Bundle savedInstanceState) {
    asyncRequest.delegate = this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activty_attach);
    Button retakeButton = (Button) (findViewById(R.id.retake_button));

    retakeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(AttachActivity.this, MainActivity.class);
            startActivity(intent);
        }
    });
    try {
        URL url;
        url = new URL("http://btl-cromwell:9000/api/engine/v1/version");
        asyncRequest.execute(url);
    } catch (Exception e) {
        Log.e(logtag, e.toString());
    }
}

请注意,传递给async任务的URL应该只返回包含接收请求的服务的版本号的JSON。

异步任务(asyncRequest)代码如下:

public class AsyncRequest extends AsyncTask<URL, Void, List<String>> {
    private String logtag = "AsyncRequestTask";
    public AsyncResponse delegate;
    List<String> projects = new ArrayList<String>();

    @Override
    protected void onPreExecute(){

        super.onPreExecute();
    }

    @Override
    protected List<String> doInBackground(URL... urls) {
            try {
            // Creating & connection Connection with url and required Header.
            HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestMethod("GET");   //POST or GET
            urlConnection.setRequestProperty("User-Agent", "Test");
            // CODE HANGS HERE
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
            projects.add(responseMessage);
            } catch (Exception e) {
                Log.e(logtag, e.toString());
            }
            return projects;
        }


    @Override
    protected void onPostExecute(List<String> result){
        delegate.processFinish(result);
    }
}

一旦我的请求正常工作,我将使用我实际想要返回的内容填充项目变量,但是现在我将它设置为responseMessage。我确信这只是因为我不熟悉用Java提出请求,但我已经花了好几天时间而无法解决这个问题。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

         asyncRequest.execute(url);
            asyncRequest.getStatus();
            String[] projects = asyncRequest.get();

无法同时执行.execute和.get()。

因为你永远不应该使用.get(),你最好删除那个语句。

删除asyncRequest.execute(url);之后的所有代码,并将该代码放入AsyncTask的onPostExecute中。