Vote count: 136
I am trying to do POST with HttpURLCoection(I need to use it this way, can't use HttpPost) and I'd like to add parameters to that coection such as
post.setEntity(new UrlEncodedFormEntity(nvp));
where
nvp = new ArrayList<NameValuePair>();
having some data stored in. I can't find a way how to add this ArrayList to my HttpURLCoection which is here:
HttpsURLCoection https = (HttpsURLCoection) url.openCoection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
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.
Any ideas?
asked Mar 19 '12 at 9:45
12 Answers
Vote count: 232 accepted
You can get output stream for the coection and write the parameter query string to it.
URL url = new URL("http://yoururl.com");
HttpsURLCoection co = (HttpsURLCoection) url.openCoection();
co.setReadTimeout(10000);
co.setCoectTimeout(15000);
co.setRequestMethod("POST");
co.setDoInput(true);
co.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 = co.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
co.coect();
...
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"));
}
retu result.toString();
}
answered Nov 21 '12 at 4:12
Vote count: 124
Since the NameValuePair is deprecated. Thought of sharing my code
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLCoection co = (HttpURLCoection) url.openCoection();
co.setReadTimeout(15000);
co.setCoectTimeout(15000);
co.setRequestMethod("POST");
co.setDoInput(true);
co.setDoOutput(true);
OutputStream os = co.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=co.getResponseCode();
if (responseCode == HttpsURLCoection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(co.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
retu 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"));
}
retu result.toString();
}
answered Apr 10 '15 at 12:09
Vote count: 81
If you don't need the ArrayList<NameValuePair> for parameters, this is a shorter solution that builds the query string using the Uri.Builder class:
URL url = new URL("http://yoururl.com");
HttpsURLCoection co = (HttpsURLCoection) url.openCoection();
co.setReadTimeout(10000);
co.setCoectTimeout(15000);
co.setRequestMethod("POST");
co.setDoInput(true);
co.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("firstParam", paramValue1)
.appendQueryParameter("secondParam", paramValue2)
.appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();
OutputStream os = co.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
co.coect();
answered Mar 14 '15 at 19:09
Vote count: 22
One solution is to make your own params string, this is the actual method i've been using for my latest project, you need to change args from hashtable to namevaluepair's:
private static String getPostParamString(Hashtable<String, String> params) {
if(params.size() == 0)
retu "";
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));
}
retu buf.toString();
}
POSTing the params:
OutputStreamWriter writer = new OutputStreamWriter(co.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));
Hope this help, btw this is my first answer, so if you find it helpful please vote me up, thx.
answered Mar 19 '12 at 9:56
Vote count: 13
I think I found exactly what you need. It may help others.
You can use the method UrlEncodedFormEntity.writeTo(OutputStream) .
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp);
http.coect();
OutputStream output = null;
try {
output = http.getOutputStream();
formEntity.writeTo(output);
} finally {
if (output != null) try { output.close(); } catch (IOException ioe) {}
}
answered Aug 16 '12 at 14:40
Vote count: 11
The accepted answer throws a ProtocolException at:
OutputStream os = co.getOutputStream();
because it does not enable the output for the URLCoection object. The solution should include this:
co.setDoOutput(true);
to make it work.
answered Jan 18 '13 at 12:14
Vote count: 5
If it's not too late, I'd like to share my code
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();
}
}
retu output;
}
public static URLCoection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
URL url = new URL(apiAddress);
HttpURLCoection urlCoection = (HttpURLCoection) url.openCoection();
urlCoection.setDoInput(true);
urlCoection.setDoOutput(!method.equals("GET"));
urlCoection.setRequestMethod(method);
urlCoection.setRequestProperty("Authorization", "Bearer " + accessToken);
urlCoection.setRequestProperty("Content-Type", mimeType);
OutputStream outputStream = new BufferedOutputStream(urlCoection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
urlCoection.coect();
retu urlCoection;
}
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
HttpURLCoection urlCoection = null;
try {
urlCoection = (HttpURLCoection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
InputStream inputStream;
// get stream
if (urlCoection.getResponseCode() < HttpURLCoection.HTTP_BAD_REQUEST) {
inputStream = urlCoection.getInputStream();
} else {
inputStream = urlCoection.getErrorStream();
}
// parse stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
retu response;
} catch (IOException e) {
e.printStackTrace();
retu e.toString();
} finally {
if (urlCoection != null) {
urlCoection.discoect();
}
}
// CASE 2: For JSONObject parameter
String url = "http://10.0.2.2/api/testjsonobject";
JSONObject jsonBody;
String requestBody;
HttpURLCoection urlCoection;
try {
jsonBody = new JSONObject();
jsonBody.put("Title", "BNK Title");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/08");
requestBody = Utils.buildPostParameters(jsonBody);
urlCoection = (HttpURLCoection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
...
// the same logic to case #1
...
retu response;
} catch (JSONException | IOException e) {
e.printStackTrace();
retu e.toString();
} finally {
if (urlCoection != null) {
urlCoection.discoect();
}
}
// CASE 3: For form-urlencoded parameter
String url = "http://10.0.2.2/api/token";
HttpURLCoection urlCoection;
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("useame", "useame");
stringMap.put("password", "password");
String requestBody = Utils.buildPostParameters(stringMap);
try {
urlCoection = (HttpURLCoection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
...
// the same logic to case #1
...
retu response;
} catch (Exception e) {
e.printStackTrace();
retu e.toString();
} finally {
if (urlCoection != null) {
urlCoection.discoect();
}
}
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
// do something...
}
}
answered Aug 8 '15 at 2:07
Vote count: 2
By using org.apache.http.client.HttpClient also you can easily do this with more readable way as below.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
Within try catch you can insert
// 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);
answered Mar 19 '12 at 10:01
Vote count: 2
There's a much easier approach using PrintWriter (see here )
Basically all you need is:
// set up URL coection
URL urlToRequest = new URL(urlStr);
HttpURLCoection urlCoection = (HttpURLCoection)urlToRequest.openCoection();
urlCoection.setDoOutput(true);
urlCoection.setRequestMethod("POST");
urlCoection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// write out form parameters
String postParamaters = "param1=value1¶m2=value2"
urlCoection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlCoection.getOutputStream());
out.print(postParameters);
out.close();
// coect
urlCoection.coect();
answered Feb 10 at 15:19
Vote count: 1
I use something like this:
....
SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = new BasicHttpParams();
SingleClientCoManager mgr = new SingleClientCoManager(params, sR);
HttpClient httpclient = new DefaultHttpClient(mgr, params);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
......
answered Mar 19 '12 at 10:00
Vote count: 1
Try this:
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);
You can add as many nameValuePairs as you need. And don't forget to mention the count in the list.
answered Mar 19 '12 at 10:10
Vote count: 1
To call POST/PUT/DELETE/GET Restful methods with custom header or json data the following Async class can be used
public class HttpUrlCoectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlCoectionUtlity";
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 HttpUrlCoectionUtlity (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();
HttpURLCoection urlCoection = (HttpURLCoection) url.openCoection();
urlCoection = setRequestMethod(urlCoection, requestType);
urlCoection.setCoectTimeout(TIME_OUT);
urlCoection.setReadTimeout(TIME_OUT);
urlCoection.setDoOutput(true);
urlCoection = setHeaderData(urlCoection);
urlCoection = setEntity(urlCoection);
if (urlCoection.getResponseCode() == HttpURLCoection.HTTP_OK) {
response = readResponseStream(urlCoection.getInputStream());
Logger.v(TAG, response);
}
urlCoection.discoect();
retu response;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
retu timeOut;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
Logger.e(TAG, "ALREADY CONNECTED");
}
retu 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() {
retu 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();
}
}
}
retu response.toString();
}
private HttpURLCoection setEntity(HttpURLCoection urlCoection) throws IOException {
if (getEntityString() != null) {
OutputStream outputStream = urlCoection.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");
}
retu urlCoection;
}
private HttpURLCoection setHeaderData(HttpURLCoection urlCoection) throws UnsupportedEncodingException {
urlCoection.setRequestProperty("Content-Type", "application/json");
urlCoection.setRequestProperty("Accept", "application/json");
if (getHeaderMap() != null) {
for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
urlCoection.setRequestProperty(entry.getKey(), entry.getValue());
}
} else {
Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
}
retu urlCoection;
}
private HttpURLCoection setRequestMethod(HttpURLCoection urlCoection, int requestMethod) {
try {
switch (requestMethod) {
case GET_METHOD:
urlCoection.setRequestMethod("GET");
break;
case POST_METHOD:
urlCoection.setRequestMethod("POST");
break;
case PUT_METHOD:
urlCoection.setRequestMethod("PUT");
break;
case DELETE_METHOD:
urlCoection.setRequestMethod("DELETE");
break;
case OPTIONS_METHOD:
urlCoection.setRequestMethod("OPTIONS");
break;
case HEAD_METHOD:
urlCoection.setRequestMethod("HEAD");
break;
case TRACE_METHOD:
urlCoection.setRequestMethod("TRACE");
break;
}
} catch (ProtocolException e) {
e.printStackTrace();
}
retu urlCoection;
}
public int getRequestType() {
retu requestType;
}
public void setRequestType(int requestType) {
this.requestType = requestType;
}
public URL getUrl() throws MalformedURLException {
retu new URL(url);
}
public void setUrl(String url) {
this.url = url;
}
public HashMap<String, String> getHeaderMap() {
retu headerMap;
}
public void setHeaderMap(HashMap<String, String> headerMap) {
this.headerMap = headerMap;
} }
And The Usage is
HttpUrlCoectionUtlity httpMethod = new HttpUrlCoectionUtlity (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(WiseCoectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
httpMethod.setEntityString(jsonEntity.toString());
httpMethod.execute();
answered Jan 19 at 16:54
برچسب:
نویسنده: استخدام کار
تاريخ: دوشنبه
20 ارديبهشت
1395 ساعت: 13:47