我试图做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。事实上,这并没有解决我的问题。
在我的情况下,我已经创建了这样的函数,使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;
}
一个解决方案是让你自己的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()));
您可以获取连接的输出流,并将参数查询字符串写入其中。
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();
...
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();
}
试试这个:
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。别忘了在名单上提到人数。