我正在尝试使用HttpURLConnection
执行 POST (我需要以这种方式使用它,不能使用HttpPost
)并且我想添加参数那个连接,如
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组合的原因是需要不验证证书。但这不是问题,它可以很好地发布服务器。但是我需要用论据发帖。
有什么想法吗?
重复免责声明:
早在2012年,我不知道如何将参数插入到 HTTP POST 请求中。我挂在NameValuePair
上,因为它在教程中。这个问题可能看似重复,但是,我的2012年自我阅读 other 问题,使用NameValuePair
NOT 。事实上,它并没有解决我的问题。
答案 0 :(得分:347)
您可以获取连接的输出流并将参数查询字符串写入其中。
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();
}
答案 1 :(得分:181)
因为不推荐使用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;
}
...
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();
}
答案 2 :(得分:151)
如果您不需要ArrayList<NameValuePair>
参数,这是使用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();
答案 3 :(得分: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();
}
张贴参数:
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));
答案 4 :(得分: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) {}
}
答案 5 :(得分:13)
接受的答案在以下位置抛出ProtocolException:
OutputStream os = conn.getOutputStream();
因为它不启用URLConnection对象的输出。解决方案应包括:
conn.setDoOutput(true);
让它发挥作用。
答案 6 :(得分:12)
如果还不晚,我想分享我的代码
<强> Utils.java:强>
inplace
<强> MainActivity.java:强>
True
答案 7 :(得分:8)
使用PrintWriter的方法更简单(参见here)
基本上你只需要:
// 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¶m2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();
// connect
urlConnection.connect();
答案 8 :(得分:4)
AsyncTask
通过JSONObect
方法
POST
方式发送数据
public class PostMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());
try {
JSONObject obj = new JSONObject();
obj.put("key1" , "value1");
obj.put("key2" , "value2");
wr.writeBytes(obj.toString());
Log.e("JSON Input", obj.toString());
wr.flush();
wr.close();
} catch (JSONException ex) {
ex.printStackTrace();
}
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
public static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
答案 9 :(得分:3)
试试这个:
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
。别忘了在列表中提及计数。
答案 10 :(得分:1)
通过使用org.apache.http.client.HttpClient,您可以通过以下更易读的方式轻松完成此操作。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
在try catch中你可以插入
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
答案 11 :(得分:1)
要使用自定义标头或json数据调用POST / PUT / DELETE / GET Restful方法,可以使用以下异步类
public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
POST_METHOD = 1,
PUT_METHOD = 2,
HEAD_METHOD = 3,
DELETE_METHOD = 4,
TRACE_METHOD = 5,
OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;
String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";
int TIME_OUT = 60 * 1000;
public HttpUrlConnectionUtlity (Context mContext) {
this.mContext = mContext;
this.callback = callback;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Integer... params) {
int requestType = getRequestType();
String response = "";
try {
URL url = getUrl();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection = setRequestMethod(urlConnection, requestType);
urlConnection.setConnectTimeout(TIME_OUT);
urlConnection.setReadTimeout(TIME_OUT);
urlConnection.setDoOutput(true);
urlConnection = setHeaderData(urlConnection);
urlConnection = setEntity(urlConnection);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
response = readResponseStream(urlConnection.getInputStream());
Logger.v(TAG, response);
}
urlConnection.disconnect();
return response;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
return timeOut;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
Logger.e(TAG, "ALREADY CONNECTED");
}
return response;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (TextUtils.isEmpty(response)) {
//empty response
} else if (response != null && response.equals(timeOut)) {
//request timed out
} else {
//process your response
}
}
private String getEntityString() {
return entityString;
}
public void setEntityString(String s) {
this.entityString = s;
}
private String readResponseStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
if (getEntityString() != null) {
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getEntityString());
writer.flush();
writer.close();
outputStream.close();
} else {
Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
}
return urlConnection;
}
private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (getHeaderMap() != null) {
for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
} else {
Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
}
return urlConnection;
}
private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
try {
switch (requestMethod) {
case GET_METHOD:
urlConnection.setRequestMethod("GET");
break;
case POST_METHOD:
urlConnection.setRequestMethod("POST");
break;
case PUT_METHOD:
urlConnection.setRequestMethod("PUT");
break;
case DELETE_METHOD:
urlConnection.setRequestMethod("DELETE");
break;
case OPTIONS_METHOD:
urlConnection.setRequestMethod("OPTIONS");
break;
case HEAD_METHOD:
urlConnection.setRequestMethod("HEAD");
break;
case TRACE_METHOD:
urlConnection.setRequestMethod("TRACE");
break;
}
} catch (ProtocolException e) {
e.printStackTrace();
}
return urlConnection;
}
public int getRequestType() {
return requestType;
}
public void setRequestType(int requestType) {
this.requestType = requestType;
}
public URL getUrl() throws MalformedURLException {
return new URL(url);
}
public void setUrl(String url) {
this.url = url;
}
public HashMap<String, String> getHeaderMap() {
return headerMap;
}
public void setHeaderMap(HashMap<String, String> headerMap) {
this.headerMap = headerMap;
} }
用法是
HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
JSONObject jsonEntity = new JSONObject();
try {
jsonEntity.put("key1", value1);
jsonEntity.put("key2", value2);
} catch (JSONException e) {
e.printStackTrace();
}
httpMethod.setUrl(YOUR_URL_STRING);
HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("key",value);
headerMap.put("key1",value1);
httpMethod.setHeaderMap(headerMap);
httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
httpMethod.setEntityString(jsonEntity.toString());
httpMethod.execute();
答案 12 :(得分:0)
我使用这样的东西:
SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params, sR);
HttpClient httpclient = new DefaultHttpClient(mgr, params);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
答案 13 :(得分:0)
在我的情况下,我创建了这样的函数来生成Post请求,它接受String 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;
}
答案 14 :(得分:0)
参数到 HttpURLConnection (使用 POST )和 NameValuePair 和 OutPut
try {
URL url = new URL("https://yourUrl.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
JSONObject data = new JSONObject();
data.put("key1", "value1");
data.put("key2", "value2");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.toString());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
答案 15 :(得分:-2)
JSONObject params = new JSONObject();
try {
params.put(key, val);
}catch (JSONException e){
e.printStackTrace();
}
这就是我通过POST传递&#34; params&#34;(JSONObject)的方法
connection.getOutputStream().write(params.toString().getBytes("UTF-8"));