Here is the method to post the image and audio File along with the data.
For multipart you need to add the libraries along with the project as below.
1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4Jand add apache-mime4j-0.6.1.jar to your project.
2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.
and here is the method of the posting the image and data to service.
public int PostMerthodWithImage(byte[] data, String postStr, String pointNumber,
String name, String ext) {
try {
mHttpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString); \\ pass the Url of the webservice here
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Log.i("log_tag", "name :" + name + " ::::: And Ext :" + ext);
if (data != null) {
bab = new ByteArrayBody(data, name.trim() + ".".trim()
+ ext.trim());
image_video_name = name.trim() + ".".trim() + ext.trim();
multipartEntity.addPart("image_video", bab);
multipartEntity.addPart("image_video_name", new StringBody(
image_video_name, Charset.forName("UTF-8")));
Log.i("log_tag", "At send image_video_name :"
+ image_video_name);
} else {
bab = null;
image_video_name = null;
}
// multipartEntity.addPart("image_video", bab);
// Log.i("log_tag", "At send bytearray :" + bab.toString());
multipartEntity.addPart("point_id", new StringBody(pointNumber,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send point_id :" + pointNumber);
multipartEntity.addPart("user_id",
new StringBody("1", Charset.forName("UTF-8")));
Log.i("log_tag", "At send user_id :" + "1");
multipartEntity.addPart("comment_text", new StringBody(postStr,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send comment_text :" + postStr);
multipartEntity.addPart(
"date",
new StringBody("" + System.currentTimeMillis(), Charset
.forName("UTF-8")));
Log.i("log_tag", "At send date :" + System.currentTimeMillis());
httppost.setEntity(multipartEntity);
HttpResponse response1 = mHttpClient.execute(httppost);
HttpEntity r_entity = response1.getEntity();
String Response = EntityUtils.toString(r_entity);
JSONObject jobj = null;
try {
jobj = new JSONObject(Response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Joj = jobj.getString("status");
} catch (Exception e) {
}
Log.i("log_tag", "Response from server :" + Response);
mHttpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.e(HttppostClient.class.getName(), e.getLocalizedMessage(), e);
}
if (Joj == "1") {
return 1;
} else {
return 0;
}
}
Search This Blog
Showing posts with label HttpPost. Show all posts
Showing posts with label HttpPost. Show all posts
Sunday, March 24, 2013
Sunday, March 3, 2013
Calling the web-service in android with POST and GET method
Hello guys Here i am posting the method of calling the webservice in android using POST and GET method.
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Now here is the calling example of the method.
client.AddParam("param1", "String of param1");
client.AddParam("param2", "String of param2");
client.AddParam("Email", email);
client.AddParam("Passwd", passcode);
try {
client.Execute(RequestMethod.POST); // OR GET
}
catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Sunday, December 30, 2012
Calling the PHP web service in android and fetch the result in Android
Suppose the url of the php webservice is as follow :
http://XX.XX.XXX.XX/~serverji/home_expanditure/gethistory.php?uid=4&month=10&year=2012
XX.XX.XXX.XX stands for the server IP.
And the response from the this url is like this :
{"date":["2012-10-13","2012-10-11","2012-10-08"],"category":["The Food Expense","rent","Communication costs"],"description":["nasto","google","fii"],"expenditure":["40","100","123"]}
Then we have to go for this kind of requesting to the url :
public class HistoryDto {
String date;
String category;
String descri;
float expe;
}
static String url = "http://XX.XX.XX.XXX/~serverji/home_expanditure/";
public static ArrayList<HistoryDto> gethistory(int month, String year) {
String result = "";
InputStream is = null;
ArrayList<HistoryDto> hisList = new ArrayList<HistoryDto>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid", Myapplication
.getuserID()));
nameValuePairs.add(new BasicNameValuePair("month", "" + month));
nameValuePairs.add(new BasicNameValuePair("year", year));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "gethistory.php?");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString().trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
JSONArray JArray_date = jObj.getJSONArray("date");
JSONArray JArray_cat = jObj.getJSONArray("category");
JSONArray JArray_dis = jObj.getJSONArray("description");
JSONArray JArray_exp = jObj.getJSONArray("expenditure");
for (int i = 0; i < JArray_date.length(); i++) {
HistoryDto dto = new HistoryDto();
dto.date = JArray_date.getString(i);
dto.category = JArray_cat.getString(i);
dto.descri = JArray_dis.getString(i);
dto.expe = (float) JArray_exp.getDouble(i);
hisList.add(dto);
}
} catch (JSONException e) {
e.printStackTrace();
}
return hisList;
}
This is how we got the result to the ArrayList and populate in the android Activities.
http://XX.XX.XXX.XX/~serverji/home_expanditure/gethistory.php?uid=4&month=10&year=2012
XX.XX.XXX.XX stands for the server IP.
And the response from the this url is like this :
{"date":["2012-10-13","2012-10-11","2012-10-08"],"category":["The Food Expense","rent","Communication costs"],"description":["nasto","google","fii"],"expenditure":["40","100","123"]}
Then we have to go for this kind of requesting to the url :
public class HistoryDto {
String date;
String category;
String descri;
float expe;
}
static String url = "http://XX.XX.XX.XXX/~serverji/home_expanditure/";
public static ArrayList<HistoryDto> gethistory(int month, String year) {
String result = "";
InputStream is = null;
ArrayList<HistoryDto> hisList = new ArrayList<HistoryDto>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid", Myapplication
.getuserID()));
nameValuePairs.add(new BasicNameValuePair("month", "" + month));
nameValuePairs.add(new BasicNameValuePair("year", year));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "gethistory.php?");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString().trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
JSONArray JArray_date = jObj.getJSONArray("date");
JSONArray JArray_cat = jObj.getJSONArray("category");
JSONArray JArray_dis = jObj.getJSONArray("description");
JSONArray JArray_exp = jObj.getJSONArray("expenditure");
for (int i = 0; i < JArray_date.length(); i++) {
HistoryDto dto = new HistoryDto();
dto.date = JArray_date.getString(i);
dto.category = JArray_cat.getString(i);
dto.descri = JArray_dis.getString(i);
dto.expe = (float) JArray_exp.getDouble(i);
hisList.add(dto);
}
} catch (JSONException e) {
e.printStackTrace();
}
return hisList;
}
This is how we got the result to the ArrayList and populate in the android Activities.
Subscribe to:
Posts (Atom)