使用HttpClient下载总是返回空响应

时间:2015-10-26 15:22:36

标签: java android download

我是android编程的新手,我想制作一个小程序从特定的API-URL下载字符串。 (我对整个编程并不陌生。)

现在我坚持使用以下代码,只是为了从url下载我的字符串:

String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
Object taskResult = new DownloadString().execute(urlToDownloadToken);

下载类的实现如下。在callbnack函数中,我有一个理论上应该显示数据的toast,但它总是做一个emty toast(我找到的代码来自这里:https://stackoverflow.com/a/14418213):

编辑:应用建议后使用OkHttp

的完整来源
public class MusicScroll extends AppCompatActivity {

String baseUrl = "http://ppcinj.com";
String token = "";

AlertDialog.Builder dlgAlert;

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

    //Set MessageBox properties...
    dlgAlert = new AlertDialog.Builder(this);
    dlgAlert.setCancelable(true);
    dlgAlert.setTitle("Message from Application");
    dlgAlert.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    try {
        String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
        token = downloadString(urlToDownloadToken);
    } catch (Exception e) {
        dlgAlert.setMessage("Error downloading data: " + e.getMessage());
        dlgAlert.create().show();
    }

    dlgAlert.setMessage(token);
    dlgAlert.create().show();
}

OkHttpClient client = new OkHttpClient();

String downloadString(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

} 有没有什么方法可以像C#的WebClient一样简单下载?

亲切的问候:)

编辑2:使用以下代码:)

public class MusicScroll extends AppCompatActivity {

String baseUrl = "http://ppcinj.tk:5656";
String token = "";

AlertDialog.Builder dlgAlert;

Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        if (message.what == 1) {
            Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
        }
    }
};

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

    //Set MessageBox properties...
    dlgAlert = new AlertDialog.Builder(this);
    dlgAlert.setCancelable(true);
    dlgAlert.setTitle("Message from Application");
    dlgAlert.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    try {
        String urlToDownloadToken = baseUrl + "?action=login&username=michael&password=qwerty123";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(urlToDownloadToken)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("BNK", e.toString());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.i("BNK", response.toString());
                token = response.body().string();
                Message msg = mHandler.obtainMessage(1);
                msg.sendToTarget();
            }
        });
    } catch (Exception e) {
        dlgAlert.setMessage("Error downloading data: " + e.getMessage());
        dlgAlert.create().show();
    }
}

public void showToken()
{
    Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
}

}

2 个答案:

答案 0 :(得分:1)

HttpClient已经deprecated多年,已从Android 6中移除。您应该使用OkHttp代替它,这是新标准。它 更容易:)。

答案 1 :(得分:0)

您可以参考以下示例代码:

array(
    'status' => array(
        'active' => 10, 
        'inactive' => 2, 
        'deleted' => 3,
    ),
    'roles' => array(
        'admin' => 2, 
        'user', 
        'editor'
    ),
    ....,
    'more-fields' => array(
        'more-values', 
    )
)

// In this example you can see we have not covered the fields of the table when they are more than 1 on save.It looks we need to build the array with values first.

foreach ($config as $table => $fields) {
    foreach ($fields as $field => $values ) {
        foreach ($values as $key => $statusCount) {
            if (is_string($key)) {
                $model = new User();
                $model->$field = $key;
                $model->another = 'value';
                $model->save();
            } else {            
                for ($i = 0; $i< $statusCount; $i++) {
                    $model = new User();
                    $model->$field = $key;
                    $model->another = 'value';
                    $model->save();
                }
            }
        }
    }
}

以下是logcat

的屏幕截图

BNK's screenshot

希望这有帮助!