我试图做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。事实上,这并没有解决我的问题。
如果你不需要ArrayList<NameValuePair>作为参数,这是一个更短的解决方案,它使用Uri构建查询字符串。建筑类:
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();
如果你不需要ArrayList<NameValuePair>作为参数,这是一个更短的解决方案,它使用Uri构建查询字符串。建筑类:
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();
您可以获取连接的输出流,并将参数查询字符串写入其中。
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();
}
要使用自定义头或json数据调用POST/PUT/DELETE/GET Restful方法,可以使用以下Async类
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();