如何使用NameValuePair使用POST向HttpURLConnection添加参数

Mic*_*hal 252 post android http-post httpurlconnection basicnamevaluepair

我试图做POSTHttpURLConnection(我需要使用这种方式,不能使用HttpPost),我想参数添加到连接如

post.setEntity(new UrlEncodedFormEntity(nvp));
Run Code Online (Sandbox Code Playgroud)

哪里

nvp = new ArrayList<NameValuePair>();
Run Code Online (Sandbox Code Playgroud)

有一些数据存储在.我找不到如何将此添加ArrayList到我HttpURLConnection这里的方法:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
Run Code Online (Sandbox Code Playgroud)

这种尴尬的https和http组合的原因是不需要验证证书.但这不是问题,它可以很好地发布服务器.但是我需要用论据发帖.

有任何想法吗?


重复免责声明:

回到2012年,我不知道如何将参数插入到HTTP POST请求中.我一直在坚持,NameValuePair因为它是在教程中.这个问题可能看似重复,但是,我的2012年自我阅读了其他问题并且它没有使用NameValuePair.事实上,它并没有解决我的问题.

小智 355

您可以获取连接的输出流并将参数查询字符串写入其中.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();
Run Code Online (Sandbox Code Playgroud)

...

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}
Run Code Online (Sandbox Code Playgroud)

  • NameValuePair也可以用AbstractMap的SimpleEntry替代.请参阅此页:http://stackoverflow.com/questions/2973041/a-keyvaluepair-in-java (24认同)
  • NameValuePair在Api 22中弃用,请查看我的答案http://stackoverflow.com/a/29561084/4552938 (11认同)
  • 为了获得最佳性能,您应该在事先知道体长时调用setFixedLengthStreamingMode(int),否则调用setChunkedStreamingMode(int).否则,HttpURLConnection将被强制在传输之前缓冲内存中的完整请求主体,浪费(并可能耗尽)堆并增加延迟. (9认同)

Fah*_*him 182

由于NameValuePair已弃用.想分享我的代码

public String  performPostCall(String requestURL,
            HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

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

        return response;
    }
Run Code Online (Sandbox Code Playgroud)

....

  private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
Run Code Online (Sandbox Code Playgroud)

  • 感谢您保持最新Fahim :-) (10认同)
  • 如果您的compileSdkVersion为23(Marshmallow),则您不再可以使用NameValuePair,因为它们删除了库.我担心迁移会很痛苦,但是你的解决方案为我节省了很多时间.谢谢. (3认同)

mpo*_*lci 151

如果您不需要ArrayList<NameValuePair>for参数,这是一个使用Uri.Builder该类构建查询字符串的较短解决方案:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();
Run Code Online (Sandbox Code Playgroud)

  • 这应该是一个答案,因为不必重新发明轮子! (7认同)
  • Uri.Builder 从哪里来? (3认同)
  • 更满意的解决方案 (2认同)

小智 25

一种解决方案是制作自己的params字符串.

这是我用于最新项目的实际方法.您需要将args从hashtable更改为namevaluepair:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}
Run Code Online (Sandbox Code Playgroud)

张贴参数:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));
Run Code Online (Sandbox Code Playgroud)

  • 当然你应该编码键值对 (3认同)

Sam*_*uel 14

我想我找到了你需要的东西.它可能会帮助别人.

您可以使用UrlEncodedFormEntity.writeTo(OutputStream)方法.

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp); 
http.connect();

OutputStream output = null;
try {
  output = http.getOutputStream();    
  formEntity.writeTo(output);
} finally {
 if (output != null) try { output.close(); } catch (IOException ioe) {}
}
Run Code Online (Sandbox Code Playgroud)


Vic*_*eda 13

接受的答案抛出一个ProtocolException:

OutputStream os = conn.getOutputStream();

因为它不启用URLConnection对象的输出.解决方案应包括:

conn.setDoOutput(true);

使它工作.


BNK*_*BNK 12

如果还不晚,我想分享我的代码

Utils.java:

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }
Run Code Online (Sandbox Code Playgroud)

MainActivity.java:

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

    new APIRequest().execute();
}

private class APIRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected Object doInBackground(Void... params) {

            // Of course, you should comment the other CASES when testing one CASE

            // CASE 1: For FromBody parameter
            String url = "http://10.0.2.2/api/frombody";
            String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                return response;
            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            // CASE 2: For JSONObject parameter
            String url = "http://10.0.2.2/api/testjsonobject";
            JSONObject jsonBody;
            String requestBody;
            HttpURLConnection urlConnection;
            try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "BNK Title");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/08");
                requestBody = Utils.buildPostParameters(jsonBody);
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (JSONException | IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }           

            // CASE 3: For form-urlencoded parameter
            String url = "http://10.0.2.2/api/token";
            HttpURLConnection urlConnection;
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "username");
            stringMap.put("password", "password");
            String requestBody = Utils.buildPostParameters(stringMap);
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }                  
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            // do something...
        }
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*chy 9

使用PrintWriter有一个更容易的方法(见这里)

基本上你只需要:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();
Run Code Online (Sandbox Code Playgroud)