api 22的Android http帖子

时间:2015-09-18 11:52:37

标签: android android-asynctask http-post httprequest

我曾经这样做过httppost:

protected String doInBackground(String... params) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://example.net/xxx/query.php?action=signin");
    String result = null;

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("user", params[0]));
        nameValuePairs.add(new BasicNameValuePair("pass", params[1]));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
    return result;
}

但是你知道httpclient在api 22上被弃用了。所以我找到了一个'HttpRequest'类,你可以在这个链接中找到I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported 我这样试试:

protected String doInBackground(String... params) {
    String result = null;

    try {
        HashMap<String, String> values = new HashMap<>();
        values.put("user", params[0]); 
        values.put("pass", params[1]);
        HttpRequest req = new HttpRequest("http://example.net/xxx/query.php?action=signin");
        result = req.preparePost().withData(values).sendAndReadString();
    } catch (Exception e) {
        result = e.getMessage();
    }

    return result;
}

但它提供了一个异常,异常消息是url(“http://example.net/xxx/query.php?action=signin”)。我究竟做错了什么?谢谢。

0 个答案:

没有答案