放入Android Activity时,HTTP GET代码无响应

时间:2015-09-11 01:23:31

标签: java android httprequest httpresponse

我正在尝试编写一个应用程序,该应用程序涉及向网页发送GET请求的活动,将代码作为响应获取,然后针对一个特定字符串(获胜者的名称)对其进行解析。当我在终端上作为独立的Java代码运行时,这很好用。将它放入Android活动虽然没有结果:既不成功也不错误。

以下是MainActivity的代码:

package com.projects.appbrewers.swaghrwtracker;

package com.example.myprojects.myapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private final String USER_AGENT = "Mozilla/5.0";
    String url = "<some URL here>";
    String currentWinnerName = "";

    TextView currentWinnerLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);
        currentWinnerLabel.setText("Finding...");
        try
        {
            checkCurrentWinner();
        }
        catch (Exception e)
        {
            //print e.getMessage() to log
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //HTTP GET Request to Swagbucks HRW iframe page
    public void checkCurrentWinner() throws Exception
    {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();

        if(responseCode == 200)
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null)
            {
                response.append(inputLine);
            }
            in.close();

            // strip out your required data with a regex
            Pattern pattern = Pattern.compile(".*<div id=\"randomWinnerName\">([a-z0-9]*)</div>.*");
            Matcher matcher = pattern.matcher(response.toString());

            if (matcher.find())
            {
                currentWinnerName = matcher.group(1);
                currentWinnerLabel.setText(currentWinnerName);
            }
            else
                currentWinnerLabel.setText("Not Found!");
        }
        else
            currentWinnerLabel.setText("ERROR!");
    }
}

2 个答案:

答案 0 :(得分:1)

以下是两个选项:  1.使用AsyncTask执行HTTP GET操作

private class CheckUsernameFromUrlTask extends AsyncTask<URL, Integer, String> {
     protected String doInBackground(URL... urlToGetTheUsername) {
         String usernameFromHttpGetMethod = null;
         // code to make (similar to your checkCurrentWinner method)
         //   1. HTTP GET request
         //   2. Extract username (incl. error handling)
         return usernameFromHttpGetMethod;
     }

     protected void onProgressUpdate(Integer... progress) {
         // ignore for now, unless you want to show the progress blocking UI
     }

     protected void onPostExecute(String result) {
         // back in the UI thread. Perform all view operations
         // Handle exceptions by saving the exception thrown in 
         // doInBackground method as an instance variable of this class or
         // changing the return object to be a custom object containing
         // username and exception.
         String labelText = result == null ? "Not Found!" : result;
         currentWinnerLabel.setText(labelText );
     }
 }

然后使用AsyncTask

@Override
protected void onCreate(Bundle savedInstanceState) {
   // ...
   new CheckUsernameFromUrlTask ().execute(url1, url2, url3);
}
  1. 使用retrofit库。该库使用Callback对象通过后台线程异步获取请求,因此您不必编写AsyncTask的代码。有关示例,请参阅文档以进行改造。

答案 1 :(得分:0)

我确信这里会抛出一个NetworkOnMainThread异常,并不像你说的那样没有错误发生。所以,你只需将它放在一个单独的线程中:

new Thread(new Runnable()
{
    @Override
    public void run()
    {
         try
        {
            checkCurrentWinner();
        }
        catch (Exception e)
        {
            //print e.getMessage() to log
        }
    }
}).start();