在构建URL时应该用什么代替BasicNameValuePair?

时间:2015-05-12 06:43:45

标签: android

我使用下面的代码来构建网络的URL。我一直在使用BasicNameValuePairURLEncodedUtils来构建URL,但现在因为android 5.0都被弃用了。那么我将用什么来创建URl?

List<NameValuePair> pairs = new ArrayList<NameValuePair>();

pairs.add(new BasicNameValuePair("APPID", "0000000000000000"));
                pairs.add(new BasicNameValuePair("lat", String.valueOf(latitude)));
                pairs.add(new BasicNameValuePair("lon", String.valueOf(longitude)));
                pairs.add(new BasicNameValuePair("type", "accurate"));
                pairs.add(new BasicNameValuePair("units", "metric"));

                // Create a new URL
                URL url = new URL("http://api.openweathermap.org/data/2.5/weather" + "?" + URLEncodedUtils.format(pairs, "utf-8"));

2 个答案:

答案 0 :(得分:0)

@Samvid ...使用排球库

public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        mPostCommentResponse.requestCompleted();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mPostCommentResponse.requestEndedWithError(error);
    }
}){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("user",userAccount.getUsername());
        params.put("pass",userAccount.getPassword());
        params.put("comment", Uri.encode(comment));
        params.put("comment_post_ID",String.valueOf(postId));
        params.put("blogId",String.valueOf(blogId));

        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/x-www-form-urlencoded");
        return params;
    }
};
queue.add(sr);
}

public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}

这是基本的例子......你可以使用acc。根据您的需要

答案 1 :(得分:0)

在我的代码中,我用一个非常简单的小型自编类替换它 - 在我的例子中是一个内部类: https://github.com/murraycu/android-galaxyzoo/commit/38964e79fa4eb36ced4a14e3d2565b6e78763080

public static class NameValuePair {
        private final String name;
        private final String value;

        public NameValuePair(final String name, final String value) {
            this.name = name;
            this.value = value;
        }

        String getName() {
            return name;
        }

        String getValue() {
            return value;
        }
    }

BasicNameValuePair的弃用评论确实无用。

但是,这不是构建网址的原因。