Android Studio -名称值对和HttpParams已弃用

hwamh0ep  于 2022-12-13  发布在  Android
关注(0)|答案(5)|浏览(167)

我是Android开发的新手,我有一些过时的问题。在Android Studio中,它声明NameValuePairHttpParams是过时的。

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("fname", user.fname));
        dataToSend.add(new BasicNameValuePair("lname", user.lname));
        dataToSend.add(new BasicNameValuePair("email", user.email));
        dataToSend.add(new BasicNameValuePair("password", user.password)); 

HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDRESS + "register");

在搜索答案时,我被派去使用openconnection(),但我不明白这如何适用于上面的代码。

63lcw9qa

63lcw9qa1#

您必须在build.gradle文件中添加HttpClient的依赖项:

android {

compileSdkVersion 23

buildToolsVersion "22.0.1"

useLibrary 'org.apache.http.legacy'

...

}
sc4hvdpw

sc4hvdpw2#

是否尝试使用ContentValues?
从这段代码中,我不确定它是否对您有帮助。

ContentValues values=new ContentValues();

  values.put("fname",user.fname);
  values.put("lname", user.lname);
  values.put("email",user.email);
  values.put("password",user.password);
hkmswyz6

hkmswyz63#

您可以根据自己喜好使用contentvalues或hashmap。
我已使用内容值

ContentValues contentValues = new ContentValues();
contentValues.put("key1","value1");
contentValues.put("key2","value2");

如果你发布的数据是表单数据,那么下面是你如何将其转换为表单数据

public String getFormData(ContentValues contentValues) throws UnsupportedEncodingException {

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, Object> entry : contentValues.valueSet()) {
        if (first)
            first = false;
        else
            sb.append("&");

        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        sb.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
    }
    return sb.toString();
}
xhv8bpkk

xhv8bpkk4#

请为NameValuePairHttpclient添加以下依赖项以使其正常工作。

dependencies{
      compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
hmae6n7t

hmae6n7t5#

只需在gradle中添加依赖项:

dependencies{
  implementation'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

相关问题