DefaultHttpClient和HttpPost德precated,使用HttpURLConnection类职位,但越来越错误:错误的参数 [英] DefaultHttpClient and HttpPost deprecated, using HttpURLConnection POST but getting ERROR: WRONG PARAMETERS

查看:193
本文介绍了DefaultHttpClient和HttpPost德precated,使用HttpURLConnection类职位,但越来越错误:错误的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我与 HttpURLConnection类类的战斗。早些时候,我只是这样做:

  DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(参数,可以UTF-8));HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();返回httpEntity.getContent();

不过,由于几乎所有的这是pcated我决定,我要改变德$ P $。我试着用下面的code来替代它:

  / **
 *
 * @参数urlString
 * @参数PARAMS
 * @返回
 *引发IOException
 * /
公众的InputStream getStreamFromConnection(字符串urlString,ContentValues​​ PARAMS)抛出IOException
    HttpURLConnection的连接= NULL;    如果(ConnectionDetector.isConnectedToInternet(this.context)){
        尝试{
            StringBuilder的urlBuilder =新的StringBuilder(urlString);
            StringBuilder的paramsBuilder =新的StringBuilder();            INT I = 0;            对于(字符串键:params.keySet()){
                paramsBuilder.append((我== 0:&放大器;)+键+=+ URLEn coder.en code(params.get(密钥)的ToString(),UTF8 ));
                我++;
            }            Log.v(连接,这是我的URL:+ urlBuilder.toString());            网址URL =新的URL(urlBuilder.toString());            连接=(HttpURLConnection类)url.openConnection();
            connection.setRequestMethod(POST);
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setDoInput(真);
            connection.setDoOutput(真);
            connection.setChunkedStreamingMode(0);            Log.v(连接,这些都是我的PARAMS:+ paramsBuilder.toString());            DataOutputStream类的OutputStream =新的DataOutputStream类(connection.getOutputStream());
            outputStream.write(paramsBuilder.toString()的getBytes());
            outputStream.flush();
            outputStream.close();            返回connection.getInputStream();
        } {最后
            如果(连接!= NULL){
                connection.disconnect();
            }
        }
    }其他{
        返回null;
    }
}

但现在我总是从我的参数是错误的服务器的消息。是不是我的新code就像我的老code同样的事情?
可能是什么问题我的参数?是否有一个函数,这样我可以看到发送到服务器整个URL字符串?

  8366-8599 / de.myPackage.myApp V /连接:这是我的网址:http://myUrl.com/mobile_login.php
8366-8599 / de.myPackage.myApp V /连接:这是我的PARAMS: email=my%40email.com&password=B5FDA3381CDE21D59843ACC16572127F45078770A331D9BE9085719A5BD35ACF46D&login_request=1
8366-8599 / de.myPackage.myApp V /连接:错误:错误的参数
8366-8599 / de.myPackage.myApp V / JSONParser:07-27 20:18:39.469 8366:8599 V / JSONParser]


解决方案

这很难说,到底是什么在你的code去错了,但我刚拿到这个简单的例子与电子邮件工作密码 login_request 参数。

首先,这里是与HttpURLConnection类方法:

 公开的JSONObject makeHtt prequest(字符串URL,
                                  HashMap的<字符串,字符串> PARAMS){    StringBuilder的sbParams =新的StringBuilder();
    StringBuilder的结果=新的StringBuilder();
    字符串charset =UTF-8;
    HttpURLConnection的康恩= NULL;
    JSONObject的jObj = NULL;
    URL urlObj = NULL;
    DataOutputStream类WR = NULL;    INT I = 0;
    对于(字符串键:params.keySet()){
        尝试{
            如果(ⅰ!= 0){
                sbParams.append(与&);
            }
            sbParams.append(键).append(=)
                    .append(URLEn coder.en code(params.get(键),字符集));        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }
        我++;
    }    Log.d(HTTP请求,params:一个+ sbParams.toString());    尝试{
        urlObj =新的URL(网址);        康恩=(HttpURLConnection类)urlObj.openConnection();        conn.setDoOutput(真);        conn.setRequestMethod(POST);        conn.setRequestProperty(接收字符集,字符集);        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);        conn.connect();        串paramsString = sbParams.toString();        WR =新的DataOutputStream类(conn.getOutputStream());
        wr.writeBytes(paramsString);
        wr.flush();
        wr.close();    }赶上(IOException异常五){
        e.printStackTrace();
    }    尝试{
        //接收来自服务器的响应
        在的InputStream =新的BufferedInputStream(conn.getInputStream());
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(中));        串线;
        而((行= reader.readLine())!= NULL){
            result.append(线);
        }        Log.d(HTTP请求,结果:+ result.toString());    }赶上(IOException异常五){
        e.printStackTrace();
    }    conn.disconnect();    //尝试分析字符串到一个JSON对象
    尝试{
        jObj =新的JSONObject(result.toString());
    }赶上(JSONException E){
        Log.e(HTTP请求,错误分析数据+ e.toString());
    }    //返回JSON对象
    返回jObj;
}

下面是我用来测试上述方法AsyncTask的:

 类PostAsyncTest扩展的AsyncTask<字符串,字符串,JSONObject的> {    私人ProgressDialog pDialog;    私有静态最后弦乐LOGIN_URL =htt​​p://www.example.com/testPost.php;    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_MESSAGE =消息;
    @覆盖
    在preExecute保护无效(){
        pDialog =新ProgressDialog(MainActivity.this);
        pDialog.setMessage(试图登录...);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真);
        pDialog.show();
    }    @覆盖
    受保护的JSONObject doInBackground(字符串参数... args){        尝试{
            HashMap的<字符串,字符串> PARAMS =新的HashMap<>();
            params.put(电子邮件,ARGS [0]);
            params.put(密码,ARGS [1]);
            params.put(login_request,ARGS [2]);            JSONObject的JSON = makeHtt prequest(
                    LOGIN_URL,则params);            如果(JSON!= NULL){
                Log.d(HTTP异步,JSON结果:+ json.toString());                返回JSON;
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回null;
    }    保护无效onPostExecute(JSON的JSONObject){        INT成功= 0;
        字符串消息=;        如果(pDialog =空&放大器;!&放大器; pDialog.isShowing()){
            pDialog.dismiss();
        }        如果(JSON!= NULL){
            Toast.makeText(MainActivity.this,json.toString(),
                    Toast.LENGTH_LONG).show();            尝试{
                成功= json.getInt(TAG_SUCCESS);
                消息= json.getString(TAG_MESSAGE);
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }        如果(成功== 1){
            Log.d(HTTP异步,成功了!+消息);
        }其他{
            Log.d(HTTP异步,失败+消息);
        }
    }}

下面是我如何执行的AsyncTask的:

 字符串email =my_email@example.com;
    字符串密码=myPasswordIsVery5ecur3;
    串loginRequest =1;
    新PostAsyncTest()执行(电子邮件,密码,loginRequest)。

下面是简单的PHP code我用来测试:

< PHP  //数组JSON响应
$响应=阵列();//检查必填字段
如果(使用isset($ _ POST [电子邮件])及和放大器;使用isset($ _ POST ['密码'])及和放大器;使用isset($ _ POST ['login_request'])){    $ NAME = $ _ POST [电子邮件];
    $消息= $ _ POST ['密码'];
    $ loginrequest = $ _ POST ['login_request'];    $响应[成功] = 1;
    $响应[消息] =登录成功。    //呼应JSON响应
    打印(json_en code($响应));
 }其他{
    //必填字段缺失
    $响应[成功] = 0;
    $响应[消息] =必填字段(S)失踪;    //呼应JSON响应
    打印(json_en code($响应));
}
?>

和,结果如下:

D / HTTP请求:params:一个密码= myPasswordIsVery5ecur3&安培;电子邮件= MY_EMAIL%40example.com&安培; login_request = 1
 D / HTTP请求:结果:{成功:1,消息:登录成功。}
 D /异步HTTP:JSON结果:{消息:登录成功,成功:1}
 D /异步HTTP:成功了!登陆成功。

Right now I'm fighting with the HttpURLConnection class. Earlier I simply did this:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

return httpEntity.getContent();

But since nearly everything of that is deprecated I decided that I have to change that. I tried to replace it with the following code:

/**
 * 
 * @param urlString
 * @param params
 * @return
 * @throws IOException
 */
public InputStream getStreamFromConnection(String urlString, ContentValues params) throws IOException {
    HttpURLConnection connection = null;

    if(ConnectionDetector.isConnectedToInternet(this.context)) {
        try {
            StringBuilder urlBuilder = new StringBuilder(urlString);
            StringBuilder paramsBuilder = new StringBuilder();

            int i = 0;

            for (String key : params.keySet()) {
                paramsBuilder.append((i == 0 ? "" : "&") + key + "=" + URLEncoder.encode(params.get(key).toString(), "utf8"));
                i++;
            }

            Log.v("Connection", "This is my URL: " + urlBuilder.toString());

            URL url = new URL(urlBuilder.toString());

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);

            Log.v("Connection", "These are my Params: " + paramsBuilder.toString());

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsBuilder.toString().getBytes());
            outputStream.flush();
            outputStream.close();

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

But now I always get the message from the server that my parameters are wrong. Isn't my new code the exact same thing like my old code? What could be wrong with my parameters? Is there a function so that I can see the whole url string sent to the server?

8366-8599/de.myPackage.myApp V/Connection﹕ This is my URL: http://myUrl.com/mobile_login.php
8366-8599/de.myPackage.myApp V/Connection﹕ These are my Params: email=my%40email.com&password=B5FDA3381CDE21D59843ACC16572127F45078770A331D9BE9085719A5BD35ACF46D&login_request=1
8366-8599/de.myPackage.myApp V/Connection﹕ ERROR: WRONG PARAMETERS
8366-8599/de.myPackage.myApp V/JSONParser﹕ [ 07-27 20:18:39.469  8366: 8599 V/JSONParser ]

解决方案

It's hard to tell exactly what is going wrong in your code, but I just got this simple example working with email, password, and login_request parameters.

First, here's the method with the HttpURLConnection:

public JSONObject makeHttpRequest(String url,
                                  HashMap<String, String> params) {

    StringBuilder sbParams = new StringBuilder();
    StringBuilder result = new StringBuilder();
    String charset = "UTF-8";
    HttpURLConnection conn = null;
    JSONObject jObj = null;
    URL urlObj = null;
    DataOutputStream wr = null;

    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    Log.d("HTTP Request", "params: " + sbParams.toString());

    try {
        urlObj = new URL(url);

        conn = (HttpURLConnection) urlObj.openConnection();

        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Accept-Charset", charset);

        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);

        conn.connect();

        String paramsString = sbParams.toString();

        wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(paramsString);
        wr.flush();
        wr.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("HTTP Request", "result: " + result.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result.toString());
    } catch (JSONException e) {
        Log.e("HTTP Request", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

Here's the AsyncTask I used for testing the above method:

class PostAsyncTest extends AsyncTask<String, String, JSONObject> {

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testPost.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {
            HashMap<String, String> params = new HashMap<>();
            params.put("email", args[0]);
            params.put("password", args[1]);
            params.put("login_request", args[2]);

            JSONObject json = makeHttpRequest(
                    LOGIN_URL, params);

            if (json != null) {
                Log.d("HTTP Async", "JSON result: " + json.toString());

                return json;
            }

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

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("HTTP Async", "Success! " +  message);
        }else{
            Log.d("HTTP Async", "Failure " + message);
        }
    }

}

Here's how I executed the AsyncTask:

    String email = "my_email@example.com";
    String password = "myPasswordIsVery5ecur3";
    String loginRequest = "1";
    new PostAsyncTest().execute(email, password, loginRequest);

Here is the simple PHP code I used to test:

<?php

  // array for JSON response
$response = array();

// check for required fields
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['login_request'])) {

    $name = $_POST['email'];
    $message = $_POST['password'];
    $loginrequest = $_POST['login_request'];

    $response["success"] = 1;
    $response["message"] = "Login successful.";

    // echoing JSON response
    print(json_encode($response));


 } else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) missing";

    // echoing JSON response
    print(json_encode($response));
}
?> 

And, the result:

 D/HTTP Request﹕ params: password=myPasswordIsVery5ecur3&email=my_email%40example.com&login_request=1
 D/HTTP Request﹕ result: {"success":1,"message":"Login successful."}
 D/HTTP Async﹕ JSON result: {"message":"Login successful.","success":1}
 D/HTTP Async﹕ Success! Login successful.

这篇关于DefaultHttpClient和HttpPost德precated,使用HttpURLConnection类职位,但越来越错误:错误的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆