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

post.setEntity(new UrlEncodedFormEntity(nvp));

在哪里

nvp = new ArrayList<NameValuePair>();

有一些数据存储在。我找不到一种方法如何添加这个数组列表到我的HttpURLConnection在这里:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

出现这种尴尬的https和http组合的原因是不需要验证证书。不过,这不是问题,它可以很好地发布服务器。但我需要它来张贴论点。

什么好主意吗?


重复的免责声明:

早在2012年,我还不知道如何在HTTP POST请求中插入参数。我一直在使用NameValuePair,因为它在教程中。这个问题可能看起来像一个重复的问题,然而,我2012年自己读了另一个问题,它没有使用NameValuePair。事实上,这并没有解决我的问题。


当前回答

使用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();

其他回答

一个解决方案是让你自己的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();
}

发布参数:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));

在我的情况下,我已经创建了这样的函数,使Post请求字符串url和参数hashmap

 public  String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
    String response="";
    try {
        URL url = new URL(mainUrl);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : parameterList.entrySet())
        {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");




        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; )
            sb.append((char) c);
        response = sb.toString();


    return  response;
    }catch (Exception excep){
        excep.printStackTrace();}
    return response;
}
JSONObject params = new JSONObject();
try {
   params.put(key, val);
}catch (JSONException e){
   e.printStackTrace();
}

这就是我如何通过POST传递“params”(JSONObject)

connection.getOutputStream().write(params.toString().getBytes("UTF-8"));

试试这个:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

String ret = EntityUtils.toString(response.getEntity());
Log.v("Util response", ret);

您可以根据需要添加任意数量的nameValuePairs。别忘了在名单上提到人数。

我想我找到了你需要的东西。它可能会帮助其他人。

你可以使用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) {}
}