本文介绍了如何使用POST参数添加到的HttpURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图做的发布与的HttpURLConnection (我需要用这种方式,不能使用 HttpPost ),我想参数添加到连接,如
I am trying to do POST with HttpURLConnection(I need to use it this way, can't use HttpPost) and I'd like to add parameters to that connection such as
post.setEntity(new UrlEncodedFormEntity(nvp));
其中
nvp = new ArrayList<NameValuePair>();
其上存储一些数据,我不能找到一种方法如何添加此的ArrayList 我的的HttpURLConnection 这是在这里:
HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; http.setRequestMethod("POST"); http.setDoInput(true); http.setDoOutput(true);
这其中的原因尴尬HTTPS和HTTP的组合是需要的不检查的证书。这是没有问题的,但是,它张贴服务器很好。但我需要它来发布带有参数。
The reason for that awkward https and http combination is the need for not verifying the certificate. That is not a problem, though, it posts the server well. But I need it to post with arguments.
任何想法?
推荐答案您可以得到的输出流的连接,并写入参数查询字符串给它。
You can get output stream for the connection and write the parameter query string to it.
URL url = new URL("yoururl"); 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(); }更多推荐
如何使用POST参数添加到的HttpURLConnection
发布评论