我试图做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。事实上,这并没有解决我的问题。
通过使用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);
要使用自定义头或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();
参数到HttpURLConnection使用POST使用NameValuePair输出
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();
}
如果还来得及的话,我想分享一下我的代码
Utils.java:
public static String buildPostParameters(Object content) {
String output = null;
if ((content instanceof String) ||
(content instanceof JSONObject) ||
(content instanceof JSONArray)) {
output = content.toString();
} else if (content instanceof Map) {
Uri.Builder builder = new Uri.Builder();
HashMap hashMap = (HashMap) content;
if (hashMap != null) {
Iterator entries = hashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove(); // avoids a ConcurrentModificationException
}
output = builder.build().getEncodedQuery();
}
}
return output;
}
public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
URL url = new URL(apiAddress);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(!method.equals("GET"));
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
urlConnection.setRequestProperty("Content-Type", mimeType);
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
urlConnection.connect();
return urlConnection;
}
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new APIRequest().execute();
}
private class APIRequest extends AsyncTask<Void, Void, String> {
@Override
protected Object doInBackground(Void... params) {
// Of course, you should comment the other CASES when testing one CASE
// CASE 1: For FromBody parameter
String url = "http://10.0.2.2/api/frombody";
String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
InputStream inputStream;
// get stream
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
// parse stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
return response;
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// CASE 2: For JSONObject parameter
String url = "http://10.0.2.2/api/testjsonobject";
JSONObject jsonBody;
String requestBody;
HttpURLConnection urlConnection;
try {
jsonBody = new JSONObject();
jsonBody.put("Title", "BNK Title");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/08");
requestBody = Utils.buildPostParameters(jsonBody);
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
...
// the same logic to case #1
...
return response;
} catch (JSONException | IOException e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// CASE 3: For form-urlencoded parameter
String url = "http://10.0.2.2/api/token";
HttpURLConnection urlConnection;
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "username");
stringMap.put("password", "password");
String requestBody = Utils.buildPostParameters(stringMap);
try {
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
...
// the same logic to case #1
...
return response;
} catch (Exception e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
// do something...
}
}