Easy Way To Do Post On Httpurlconnection?
what is the easiest way to do POST on HTTPURLCONNECTION in AsyncTask on android? I just want to post data on my php file which will then return me a json response
Solution 1:
You can piece it together from this answer I gave you the other day: How to get JSON object using HttpURLConnection instead of Volley?
... and the answer here: Java - sending HTTP parameters via POST method easily
That being said, the easiest way to get started sending POST data and getting a JSON result is to just use the old APIs.
Here's a working example:
classCreateNewProductextendsAsyncTask<String, String, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
/**
* Before starting background thread Show Progress Dialog
* */@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();
pDialog = newProgressDialog(ShareNewMessage.this);
pDialog.setMessage("Sharing Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */protectedJSONObjectdoInBackground(String... args) {
String message = inputMessage.getText().toString();
// Building ParametersList<NameValuePair> params = newArrayList<NameValuePair>();
params.add(newBasicNameValuePair("name", username));
params.add(newBasicNameValuePair("message", message));
Log.d("Share", "Sharing message, username: " + username + " message: " + message);
try {
DefaultHttpClient httpClient = newDefaultHttpClient();
HttpPost httpPost = newHttpPost(url_create_message);
httpPost.setEntity(newUrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = newBufferedReader(newInputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = newStringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Share", "Error converting InputStream result " + e.toString());
}
// try parse the string to a JSON objecttry {
jObj = newJSONObject(json);
} catch (JSONException e) {
Log.e("Share", "Error parsing JSON data " + e.toString());
}
try{
int success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
/**
* After completing background task Dismiss the progress dialog
* **/protectedvoidonPostExecute(JSONObject jObj) {
//do something with jObj// dismiss the dialog once done
pDialog.dismiss();
}
}
Solution 2:
Here is a sample code of how to upload an image to a server
classImageUploadTaskextendsAsyncTask <Void, Void, String>{
@Overrideprotected String doInBackground(Void... unsued) {
try {
HttpClienthttpClient=newDefaultHttpClient();
HttpContextlocalContext=newBasicHttpContext();
HttpPosthttpPost=newHttpPost(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntityentity=newMultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStreambos=newByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", newStringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", newStringBody("json"));
entity.addPart("uploaded", newByteArrayBody(data,
"myImage.jpg"));
entity.addPart("photoCaption", newStringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponseresponse= httpClient.execute(httpPost,
localContext);
BufferedReaderreader=newBufferedReader(
newInputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringsResponse= reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
returnnull;
}
// (null);
}
For the complete tutorial on this, go through this.
In the above code, you can send any form data you want to send by just adding
entity.addPart("value", new StringBody(key));
Solution 3:
Try This
publicclassparseProductextendsAsyncTask<Void, Void, Void> {
String jsonResponse;
@OverrideprotectedvoidonPreExecute() {
super.onPreExecute();
}
@OverrideprotectedVoiddoInBackground(Void... params) {
JSONObjectobject = newJSONObject();
try {
object.put("registeruserid", userId); // you can pass data which you want to pass from POST
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonResponse=getResponseStringFromURL2(URL,object.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(Void resul) {
super.onPostExecute(resul);
}
}
Here is the function :
public String getResponseStringFromURL2(String url, String json)throws ClientProtocolException, IOException {
StringBuilderresult=newStringBuilder();
HttpParamshttpParameters=newBasicHttpParams();
inttimeoutConnection=30000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
inttimeoutSocket=30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClienthttpClient=newDefaultHttpClient(httpParameters);
HttpPostrequest=newHttpPost(url);
if (json != null) {
StringEntityse=newStringEntity(json);
request.setEntity(se);
}
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
Log.d("request: ", ":" + request.getRequestLine());
HttpResponseresponse=null;
response = httpClient.execute(request);
if (response == null)
returnnull;
InputStreaminput=null;
input = newBufferedInputStream(response.getEntity().getContent());
byte data[] = newbyte[40000];
intcurrentByteReadCount=0;
/** read response from inpus stream */while ((currentByteReadCount = input.read(data)) != -1) {
StringreadData=newString(data, 0, currentByteReadCount);
result.append(readData);
}
input.close();
return result.toString();
}
Post a Comment for "Easy Way To Do Post On Httpurlconnection?"