我在使用HTTP GET请求检索数据时遇到错误

时间:2017-12-12 12:28:14

标签: android

public class BackgroundWorker extends AsyncTask<String,Void,String> {


    public static final int CONNECTION_TIMEOUT=7000;
    public static final int READ_TIMEOUT=15000;
    public String type,username,password,url;
    public HttpURLConnection con;
    public StringBuilder stringBuilder;
    public InputStream input;
    public BufferedReader reader;
    public URL myURL;
    public ProgressDialog pdLoading;
    public AlertDialog alertDialog;
    public Context context;
    BackgroundWorker(Context ctxt){
        context = ctxt;
        con = null;
    }
    @Override
    protected String doInBackground(String... params) {

        this.type = params[0];
        this.url = params[1];
        this.username = params[2];
        this.password = params[3];

        if (this.type == "POST")
        {
          // here iam handle post request
        }
        if (this.type == "GET")
        {

            try {
                this.myURL = new URL(this.url);
                this.con =(HttpURLConnection) this.myURL.openConnection();
                this.con.setRequestMethod(this.type);
                this.con.setReadTimeout(READ_TIMEOUT);
                this.con.setConnectTimeout(CONNECTION_TIMEOUT);
                this.con.setRequestProperty("Content-Type", "application/json");
                this.con.setRequestProperty("Accept", "application/json");
                this.con.connect();

                this.input = this.con.getInputStream();
                this.reader = new BufferedReader(new InputStreamReader(input,"UTF-8"),8);
                stringBuilder = new StringBuilder();
                String inputLine;
                while((inputLine = reader.readLine()) != null){
                    stringBuilder.append(inputLine);
                }
                reader.close();
                return this.con.toString();
            }
            catch(IOException e){
                e.printStackTrace();
   // compiler found in catch block when iam perform get request event
                return String.format("The url %s\n%s\n%s",e.getMessage(),this.type,this.url);
            } finally {
                this.con.disconnect();
            }
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

我看不到任何Get参数附加到您的网络服务。这一定是原因。您需要使用您的请求发送参数。以下是从您的代码中获取的代码

 this.type = params[0];
    this.url = params[1];
    this.username = params[2];
    this.password = params[3];

您没有通过网络服务发送这些参数。