Android返回空字符串HTTP

时间:2015-06-18 14:46:00

标签: java php android mysql json

我有问题。我有一个类AsyncTaskActivity,其中包含通过downloadUrl与服务器php通信的方法HttpURLConnection。与MySql DB通信的服务器php应该返回一个字符串文本或json格式的字符串,具体取决于元素的类型。当服务器返回的元素类型是字符串文本时,HttpURLConnection返回一个空字符串。 这是课程AsyncTaskActivity

public class AsyncTaskActivity extends AsyncTask<String, Void, String> {
private Context context;
String serverParameters;
public AsyncResponse delegate = null;
String url = null;
private ProgressDialog pd;

public AsyncTask(Context c, String s, AsyncResponse<String> delegate) {
    this.serverParameters = s;
    this.context = c;
    this.delegate = delegate;
}

@Override
protected String doInBackground(String... strings) {
    try {
        url = downloadUrl(strings[0]);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return url;
}

protected void onPreExecute() {
    super.onPreExecute();
    pd = new ProgressDialog(context);
    pd.setTitle("Please Wait...");
    pd.setMessage("Loading...");
    pd.show();
}

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    System.out.println("RESULT = " + result);
    delegate.processFinish(result);
    pd.dismiss();
}

private String downloadUrl(String targetURL) throws IOException {
    URL url;
    HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send request
        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
        wr.write(serverParameters);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        String data = convertStreamToString(is);
        is.close();
        return data;

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

private String convertStreamToString(InputStream inputStream) {
    Scanner s = new Scanner(inputStream).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

这是班级AvailabilityActivity。当我向服务器发送请求时必须指定为参数类型元素,访问类型(读取,写入,更改,删除)和json写入。 在这种情况下,当我向服务器发送请求时(type element =“expertise”,access =“read”,json to write =“”),我获得一个空字符串。类型元素“专业知识”应返回字符串文本。 在初始化Riepilogo.setOnClickListener serverParameters后,sendRequest()执行AsyncTaskActivity()

public class AvailabilityActivity extends ActionBarActivity implements AsyncResponse<String> {
private Spinner spinner;
private Spinner spinner1;

/* Parameters Expertise*/

private static final String TIPO_ELEMENTO = "expertise";
private static final String ACCESSO = "read";
private AsyncTaskActivity send_request;
private String serverParameters;
private JSONObject jsonObject;
private ArrayList<String> list = new ArrayList<String>();
AvailabilityEntity availabilityEntity;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_availability);
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner = (Spinner) findViewById(R.id.spinner2);

    Riepilogo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            date_ = date.getText().toString();
            startTime_ = startTime.getText().toString();
            endTime_ = endTime.getText().toString();
            timeEditText_ = timeEditText.getText().toString();
            availabilityEntity = new AvailabilityEntity(date_, startTime_, endTime_, itemSpinner, timeEditText_);
            showSummary();
        }
    });

    serverParameters = generateParameters(TIPO_ELEMENTO, ACCESSO, "");
    sendRequest();
}

private String generateParameters(String tipoElementoLogin, String accesso, String s) {
    String parameters = "accesso:" + accesso + ", elemento:" + tipoElementoLogin + ", jsonDaScrivere:" + s;
    return parameters;
}

private void sendRequest() {
    send_request = new AsyncTaskActivityString(this, serverParameters, this);
    send_request.execute(getApplicationContext().getResources().getString(R.string.serverQuery));
}

@Override
public void processFinish(String output) {
    System.out.println("Value: " + output);
    // Aggiunge lista expertise dal server in spinner
    list.add(output);
    ArrayAdapter<String> array_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
    array_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(array_adapter);

}

1 个答案:

答案 0 :(得分:0)

看起来你忘了打电话给connection.connect()。 试试这段代码:

scala.collection.immutable.HashMap