How to add parameters in android http POST?
How to make an http POST and adding parameters.
how to add parameters? you must have something like.
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "12312"));
nameValuePairs.add(new BasicNameValuePair("sessionid", "234"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
This is a complete method:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/myexample.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "stackoverflow.com is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
How to post params in the body of HTTP post request?
How about:
public static String makePostRequest(String stringUrl, String payload,
Context context) throws IOException {
URL url = new URL(stringUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
String line;
StringBuffer jsonString = new StringBuffer();
uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
uc.setRequestMethod("POST");
uc.setDoInput(true);
uc.setInstanceFollowRedirects(false);
uc.connect();
OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while((line = br.readLine()) != null){
jsonString.append(line);
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
uc.disconnect();
return jsonString.toString();
}
Where payload is the body JSON string. You will also need to use an AsyncTask and run the above method in the doInBackground method, like so:
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
try {
String response = makePostRequest("http://www.example.com",
"{ exampleObject: \"name\" }", getApplicationContext());
return "Success";
} catch (IOException ex) {
ex.printStackTrace();
return "";
}
}
}.execute("");
Now you can use the response you get back from the server as well
Android httpPost with parameters and file
You must use a multipart http post, like in HTML forms. This can be done with an extra library.
See the post Sending images using Http Post for a complete example.
How to add parameters to HttpURLConnection using POST using NameValuePair
You can get output stream for the connection and write the parameter query string to it.
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();
}
Send Post Request with params using Retrofit
I have found the solution. The issue was a problem in my classes structure. So i updated them like the following samples.
public class LandingPageReport {
private ArrayList<LandingPageReportItem> GetDetailWithMonthWithCodeResult;
// + Getter Setter methods
}
public class LandingPageReportItem {
private String code;
private String field1;
// + Getter Setter methods
}
And then i use this retrofit configuration
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<LandingPageReport> cb);
Sending Parameter using POST method in Android
try and use this code:
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> params = new ArrayList<NameValuePair>();
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
params.add(new BasicNameValuePair("pkey", "pvalue"));
}
@Override
protected String doInBackground(String... param) {
// TODO Auto-generated method stub
String json;
try {
json = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", "> " + json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
Related Topics
How to Remove Shared Preference While Application Uninstall in Android
Endless Recyclerview with Progressbar for Pagination
Detect Back Button But Don't Dismiss Dialogfragment
Fileprovider Crash - Npe Attempting to Invoke Xmlresourceparser on a Null String
How to Check If an App Is a Non-System App in Android
Filtering Accelerometer Data Noise
Asynctask: Where Does the Return Value of Doinbackground() Go
Multiple Selection in Custom Listview with Cab
Programmatically Collapse a Group in Expandablelistview
How to Implement Export SQLite to Excel/CSV File in Android
Android Ndk: Link Using a Pre-Compiled Static Library
How to Iterate Through All Keys of Shared Preferences
Calling Android Dialog Without It Fading the Background
Autocompletetextview Not Completing Words Inside Parentheses
Overridependingtransition Does Not Work When Flag_Activity_Reorder_To_Front Is Used