Android 返回空字符串 HTTP

Posted

技术标签:

【中文标题】Android 返回空字符串 HTTP【英文标题】:Android returns empty string HTTP 【发布时间】:2015-09-04 06:51:48 【问题描述】:

我有问题。我有一个类AsyncTaskActivity,其中包含方法downloadUrl,它通过HttpURLConnection 与服务器php 通信。与 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 = ""),我得到一个空字符串。类型元素“expertise”应该返回一个字符串文本。 在Riepilogo.setOnClickListenerserverParameters被初始化,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);


【问题讨论】:

整个字符串是空的还是只是元素?是否可以通过浏览器测试等其他方式获取JSON字符串? 听起来问题出在服务器端 (PHP)。 哪个是可能的解决方案? class AsyncTaskActivity extends AsyncTask。不是很好。令人困惑。这与 Activity 无关。最好称它为 MyAsyncTask 或类似的名称。 如果 php 脚本发送一个文本或一个 json 文本,那么服务器总是发送一个文本。因此,当您使用相同的代码接收文本时,总是会收到文本。最好责怪php脚本。您所有的活动代码都非常多。为什么我们必须看到并阅读所有内容? 【参考方案1】:

您似乎忘记调用connection.connect()。 试试这段代码:

private String downloadUrl(String targetURL) throws IOException 
   ...
   ...

   // Get Response
   connection.connect();
   int http_code = connection.getResponseCode();

   String data = null;
   if (http_code == HttpURLConnection.HTTP_OK) 
      data = this.convertStreamToString(connection.getInputStream());
   

【讨论】:

以上是关于Android 返回空字符串 HTTP的主要内容,如果未能解决你的问题,请参考以下文章

打开远程 URL 返回空字符串?

NSDictionary 在推送通知中返回空字符串

file_get_contents 返回空字符串

JSON 对象为具有值的键返回空字符串

WebClient 请求返回空字符串

如何从 RPC 调用返回空字符串?