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();
}
How to post data using HttpURLConnection
You can do something like this:
public boolean sendPost(MessageSenderContent content) {
HttpURLConnection connection;
try {
URL gcmAPI = new URL("your_url");
connection = (HttpURLConnection) gcmAPI.openConnection();
connection.setRequestMethod("POST");// type of request
connection.setRequestProperty("Content-Type", "application/json");//some header you want to add
connection.setRequestProperty("Authorization", "key=" + AppConfig.API_KEY);//some header you want to add
connection.setDoOutput(true);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
//content is the object you want to send, use instead of NameValuesPair
mapper.writeValue(dataOutputStream, content);
dataOutputStream.flush();
dataOutputStream.close();
responseCode = connection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
if (responseCode == 200) {
Log.i("Request Status", "This is success response status from server: " + responseCode);
return true;
} else {
Log.i("Request Status", "This is failure response status from server: " + responseCode);
return false;
}
}
Example for MessageSenderContent, than you can create your own one for "message" and "id":
public class MessageSenderContent implements Serializable {
private List<String> registration_ids;
private Map<String, String> data;
public void addRegId(String regId){
if (registration_ids==null){
registration_ids = new LinkedList<>();
registration_ids.add(regId);
}
}
public void createData(String title,String message) {
if (data == null)
data = new HashMap<>();
data.put("title", title);
data.put("message", message);
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
public List<String> getRegIds() {
return registration_ids;
}
public void setRegIds(List<String> regIds) {
this.registration_ids = regIds;
}
@Override
public String toString() {
return "MessageSenderContent{" +
"registration_ids=" + registration_ids +
", data=" + data +
'}';
}
UPDATE:
You can use HttpUrlConnection after import this in your build.gradle file
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
useLibrary 'org.apache.http.legacy' // this one will let you use HttpUrlConnection
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
...
}
Passing Parameters with HttpURLConnection
I fixed it like this:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Here is parameter stuff:
String charset = "UTF-8";
String s = "unit_type=" + URLEncoder.encode(MainActivity.distance_units, charset);
s += "&long=" + URLEncoder.encode(String.valueOf(MainActivity.mLongitude), charset);
s += "&lat=" + URLEncoder.encode(String.valueOf(MainActivity.mLatitude), charset);
s += "&user_id=" + URLEncoder.encode(String.valueOf(MyndQuest.userId), charset);
conn.setFixedLengthStreamingMode(s.getBytes().length);
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(s);
out.close();
Java - sending HTTP parameters via POST method easily
In a GET request, the parameters are sent as part of the URL.
In a POST request, the parameters are sent as a body of the request, after the headers.
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
This code should get you started:
String urlParameters = "param1=a¶m2=b¶m3=c";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "http://example.com/index.php";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
Unable to get response from HttpURLConnection POST method
I managed to solved the issue. Removed this:
conn.getOutputStream().write(postDataBytes);
And send the request like this:
try(OutputStream os = conn.getOutputStream()) {
os.write(postDataBytes);
}
Related Topics
Find Location of a Removable Sd Card
Standard Android Button With a Different Color
Saving and Reading Bitmaps/Images from Internal Memory in Android
What Permission Do I Need to Access Internet from an Android Application
How to Scale an Image in Imageview to Keep the Aspect Ratio
Drawing a Line/Path on Google Maps
Disable Back Button in Android
How to Close Android Application
How to Find Out If the Gps of an Android Device Is Enabled
How to Create a Release Signed Apk File Using Gradle
Install Application Programmatically on Android
How to Detect When an Android App Goes to the Background and Come Back to the Foreground
Difference Between "@Id/" and "@+Id/" in Android
"R Cannot Be Resolved to a Variable"
Filter Logcat to Get Only the Messages from My Application in Android
How to Detect If Software Keyboard Is Visible on Android Device or Not