Reputation: 955
Good morning together,
i found a helpful tutorial for making an HTTP POST request with android. this code works fine, but i would like to know, if this code is the best way to do this, or if yo have any ideas, how i can optimize it.
private class PostClass extends AsyncTask<String, String, String> {
Context context;
public PostClass(Context c){
this.context = c;
}
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("xxxx");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "xxx";
connection.setRequestMethod("POST");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = br.readLine();
br.close();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}
}
Upvotes: 0
Views: 1643
Reputation: 341
Yes that is correct. I made a library, that looks similar to this under the hood, to handle requests like this: https://github.com/gjudkins/GjuddyRequest
add the dependency to you build.gradle:
repositories {
maven {
url 'https://dl.bintray.com/gjudkins/maven'
}
}
dependencies {
compile 'com.gjuddy:easyhttprequest:0.1.17'
}
then making the request would look something like this:
// define headers
ContentValues headers = new ContentValues();
bodyParams.put("FirstHeader","header-value");
bodyParams.put("AnotherHeader","add as many as you want");
// define parameters
ContentValues bodyParams = new ContentValues();
bodyParams.put("name","the_name");
bodyParams.put("another_param","add as many as you want");
// define how GjuddyRequest will format the body/parameters of the request
// !! The appropriate headers for the ContentType defined here are AUTOMATICALLY added to the request !!
GjuddyRequest.ContentType bodyFormat = GjuddyRequest.ContentType.x_www_url_form_urlencoded;
// make the POST request
GjuddyRequest.getInstance().makePostAsync("https://your.api.url", bodyParams, bodyFormat, headers, new GjuddyRequest.HttpRequestCallback() {
@Override
public void requestComplete(GjuddyResponse response) {
// check for errors
if (response.getErrors() == null) {
// the GjuddyResponse object can automatically retrieve the response
// as a String, JSONObject, or JSONArray
JSONObject jsonResponse = response.toJSONObject();
Log.e("GJUDDY", response.toString());
} else {
Log.e("GJUDDY", response.getErrorString());
}
}
});
The GitHub readme in the link goes into depth on how to use it, but it's pretty easy.
Upvotes: 0
Reputation: 8149
Here is example Http Post Request using Volly library
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("Your ID1");
value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
value2= null;
}
}
) {
// here is params will add to your url using post method
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
this post request is using this compile 'com.mcxiaoke.volley:library:1.0.19'
volley version.
i am just adding app name as parameter.you can add more params.
Upvotes: 0
Reputation: 4547
Based on the frequency of synchronization , you could use Volley. Also, You could use following code as well where you need to send multiple parameters in POST request.
HttpClient httpclient = new DefaultHttpClient();
String responseStr="";
String URL=Constants.API_URL;#URL where request needs to be sent
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", pick_up_id));
nameValuePairs.add(new BasicNameValuePair("driver_photo", strPhoto));#image in form of Base64 String which you need to send
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
String responseBody = EntityUtils.toString(entity);
responseStr=responseBody;
}
break;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
System.out.println("this is response "+responseStr);
Upvotes: 1