Android - Post image within json object to server using volley library - java

I want post json object included image to my server using Volley Library it post empty fields to server , image file posted successfully
I should post Json in this formate
{ "user_id":"value" , "post_title":"value","Specialty":"value","post_detail":"value", "uploaded_file","file" }
here is my android code
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.imaadv.leaynik.Util.AppConstants;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Created by NT on 10/26/15.
*/
public class PhotoMultipartRequest<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private Response.Listener<T> mListener;
private File mImageFile;
protected Map<String, String> headers;
private JSONObject params;
private String file_name;
private boolean hasFile;
public PhotoMultipartRequest(JSONObject params, String url, Response.ErrorListener errorListener, Response.Listener<T> listener, String file_name, File imageFile, boolean hasFile) {
super(Method.POST, url, errorListener);
mListener = listener;
mImageFile = imageFile;
this.params = params;
this.file_name = file_name;
this.hasFile = hasFile;
BuildMultiPartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<>();
}
headers.put("accept", "application/json");
headers.put("Content-type","application/json");
return headers;
}
private void BuildMultiPartEntity() {
// Set keys = params.keySet();
// for (Iterator i = keys.iterator(); i.hasNext(); ) {
// String key = (String) i.next();
// try {
//
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
StringBody userId = new StringBody(params.get(AppConstants.USER_ID) ,ContentType.APPLICATION_JSON);
StringBody postDetail = new StringBody(params.get(AppConstants.POST_DETAIL) ,ContentType.APPLICATION_JSON);
StringBody postTitle = new StringBody(params.get(AppConstants.POST_TITLE) ,ContentType.APPLICATION_JSON);
StringBody Speciality = new StringBody(params.get(AppConstants.SPECIALTY) ,ContentType.APPLICATION_JSON);
mBuilder.addPart(AppConstants.USER_ID ,userId );
mBuilder.addPart(AppConstants.POST_DETAIL ,postDetail );
mBuilder.addPart(AppConstants.POST_TITLE ,postTitle );
mBuilder.addPart(AppConstants.SPECIALTY ,Speciality );
mBuilder.addTextBody(AppConstants.DATA, params.toString());
if (hasFile) {
mBuilder.addBinaryBody(file_name, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
}
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.i("Error1", volleyError.getMessage());
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
Log.i("Error2", error.getMessage());
super.deliverError(error);
}
}
Could any one guide me what is wrong in my code

You can see your answer on follow this 3 link.....
Click here
http://www.survivingwithandroid.com/2013/05/android-http-downlod-upload-multipart.html
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Best Luck..

Related

how to pass header api key in volley

I am new to android and volley
I'm straggling with JSON path
spent a lot of time debugging this code but unfortunately could not find the bug, can someone help me find the issue in this code. I am not able to see data on the activity page
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class dailyshop extends AppCompatActivity {
private RecyclerView mRecycler;
private cardAdapter mCardAdapter;
private ArrayList<carditem> mCardList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dailyshop);
mRecycler = findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mCardList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
String url = "https://fortnite-api.theapinetwork.com/store/get";
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String itemName = jsonObject.getString("name");
String imageUrl = jsonObject.getString("background");
int vCount = jsonObject.getInt("cost");
mCardList.add(new carditem(imageUrl,itemName,vCount));
}
mCardAdapter = new cardAdapter(dailyshop.this, mCardList);
mRecycler.setAdapter(mCardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "mycode");
return params;
}
};
mRequestQueue.add(request);
}
}
I tried to use custom API without key in same JSON child and it worked
api json file
{
"lastUpdate":1563408000,
"language":"en",
"data":[
{
"itemId":"0ac5766-6f9355e-6575a4e-abaef79",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Glitter",
"description":"",
"type":"emote",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/emote/a7eb82676b96bc1ff2129ee739d70d4a.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.18,
"totalPoints":614,
"numberVotes":147
}
}
},
{
"itemId":"d2e8284-fb06feb-ea3fbe3-c41fd8b",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"800",
"occurrences":3,
"isNew":false
},
"item":{
"name":"Star Wand",
"description":null,
"type":"pickaxe",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/pickaxe/e0907bc2a6058035c5bf96820da6c21f.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.07,
"totalPoints":789,
"numberVotes":194
}
}
},
{
"itemId":"eb00ead-bb56b45-05e52f8-2398d3a",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"300",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Scanline",
"description":"",
"type":"wrap",
"rarity":"uncommon",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/wrap/5677d39e97ba5bf8d92e25bc520e7cc0.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.82,
"totalPoints":164,
"numberVotes":34
}
}
},
{
"itemId":"a784814-93b4ea3-3c26b6f-631fac7",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
}
}
]
}
I need help with JSON path and if there is something wrong with my code
Try this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String credentials = "username" + ":" + "password";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + base64EncodedCredentials);
return headers;
}

Get POST Result in JSON

I'm sending the data with the POST. I get the answer with JSON.
If I use plain text instead of JSON, it's working but It doesn't work with JSON.
I do not receive any error screen in the application
if (status) = true -> Register OK
IMPORT:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Result;
JSON:
[{"status":true,"result":"registerSuccessful","message":"Register succeeded"}]
JAVA Code:
private void registernewuser() {
StringRequest request = new StringRequest(Request.Method.POST, registerUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String RegisterResultString = jsonResponse.getString("status");
if (RegisterResultString.equals("true")) {
Toast.makeText(getApplicationContext(), "Successfully Registered User", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sorry, Error Registering New User", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("registeruser", "true");
params.put("username", username.getText().toString().trim());
params.put("userpassword", userpassword.getText().toString().trim());
params.put("useremail", useremail.getText().toString());
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
I'm not having trouble building applications. But I can't find my fault.
Your JSON code is a JSONArray with a single JSONObject because of square brackets. So, just set type of your jsonResponse as JSONArray and fetch a JSONObject using the JSONArray.getJSONObject(0) method.
JSONArray jsonResponse = new JSONArray(response);
String registerResultString = jsonResponse.getJSONObject(0).getString("status");
You need to add the header to your request to indicate the JSON usage :
request.addHeader("content-type", "application/json");
Else it will interpret it as plain text.
You can call the request as JSONRequest
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
your_url, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};

How to upgrade from HTTPClient to volley

In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag
Can we also do the same using volley?
How can I upgrade to Volley from the HttpClient having same approach like in below class?
package com.creative.projectmanager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* server manager class. performs all server requests asynchronously
*/
public class ServerManager {
final private String SERVER_ADDRESS = "http://192.168.200.10/";
public void login(String email, String password, int requestTag) {
String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
HashMap<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
params.put("authenticate", "false");
android.util.Log.w("My App", email + " " + password + " " + requestTag);
AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
requestSender.execute();
}
public void downloadImage(String imageUrl, int imageSize, int requestTag) {
ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
imageDownloadTask.execute();
}
private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
private String url = "";
private HashMap<String, String> postParams = null;
private int requestTag;
private String errorMessage = "";
public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
this.url = url;
postParams = params;
this.requestTag = tag;
}
#Override
protected String doInBackground(Void... params) {
byte[] result;
String resultString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
for (String key:postParams.keySet()
) {
nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
}
android.util.Log.w("My App",nameValuePairs.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
errorMessage = "ok";
result = EntityUtils.toByteArray(response.getEntity());
resultString = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
errorMessage = "Encoding is not supported";
}
catch (Exception e) {
errorMessage = "An error occurred";
}
return resultString;
}
#Override
protected void onPostExecute(String s) {
if (errorMessage.equals("ok")) {
sourceActivity.requestFinished(s, requestTag);
}
else
sourceActivity.requestFailed(errorMessage, requestTag);
}
}
private class ImageDownloadTask extends AsyncTask<String, String, String> {
private String imageUrl;
private int imageSize;
private int requestTag;
Bitmap image;
public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
this.imageUrl = imageUrl;
this.imageSize = imageSize;
this.requestTag = requestTag;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(imageUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
image = createScaledBitmapFromStream(inputStream, imageSize);
}
catch (Exception e){
//do nothing
}
return null;
}
#Override
protected void onPostExecute(String s) {
sourceActivity.imageDownloaded(image, requestTag);
}
protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
try {
BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
if (minimumDesiredBitmapSize > 0) {
BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
decodeBoundsOptions.inJustDecodeBounds = true;
bufferedInputStream.mark(32 * 1024);
BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
bufferedInputStream.reset();
int originalWidth = decodeBoundsOptions.outWidth;
int originalHeight = decodeBoundsOptions.outHeight;
decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
}
return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
}
catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedInputStream.close();
} catch (IOException ignored) {}
}
}
}
}
There are a lot of examples of how to make requests with Volley, so "upgrading" will mean rewriting your code in different way.
Volley, in my opinion is not the best library for HTTP calls, I would recommend you to try
http://square.github.io/retrofit/
for loading images use http://square.github.io/picasso/ or glide. These libraries will help you make you code cleaner whit out boilerplate stuff.

Volley: MultipartRequest.getBody: IOException writing to ByteArrayOutputStream

I am using Volley for my API call. I need to post a image to my sever.
I have tried many MultipartRequest implementation, None works.
I just tried using a sample from How to send a “multipart/form-data” POST in Android with Volley by AZ_.
But I get MultipartRequest.getBody: IOException writing to ByteArrayOutputStream Error.
Can you help me out on my code, or know any complete sample for uploading a image using Volley please. Thank you.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
//Code by:
//https://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley
//AZ_
//
/**
* Problems : E/Volley﹕ [17225] MultipartRequest.getBody: IOException writing to ByteArrayOutputStream
*/
public class MultipartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "files";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
private Map<String, String> headerParams;
private final MultipartProgressListener multipartProgressListener;
private long fileLength = 0L;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file, long fileLength,
Map<String, String> mStringPart,
final Map<String, String> headerParams, String partName,
MultipartProgressListener progLitener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.fileLength = fileLength;
this.mStringPart = mStringPart;
this.headerParams = headerParams;
this.FILE_PART_NAME = partName;
this.multipartProgressListener = progLitener;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
// public void addStringBody(String param, String value) {
// if (mStringPart != null) {
// mStringPart.put(param, value);
// }
// }
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/gif"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity.writeTo(new CountingOutputStream(bos, fileLength, multipartProgressListener));
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
// System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// it should never happen though
return Response.success(new String(response.data), getCacheEntry());
}
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
//Override getHeaders() if you want to put anything in header
public static interface MultipartProgressListener {
void transferred(long transfered, int progress);
}
public static class CountingOutputStream extends FilterOutputStream {
private final MultipartProgressListener progListener;
private long transferred;
private long fileLength;
public CountingOutputStream(final OutputStream out, long fileLength,
final MultipartProgressListener listener) {
super(out);
this.fileLength = fileLength;
this.progListener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (progListener != null) {
this.transferred += len;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
public void write(int b) throws IOException {
out.write(b);
if (progListener != null) {
this.transferred++;
int prog = (int) (transferred * 100 / fileLength);
this.progListener.transferred(this.transferred, prog);
}
}
}
}
User API Class
public void uploadFile(String api, File file, long fileLength, String partName, final UserUploadSuccessListener listener) {
this.listener = listener;
String url = Constant.DOMAIN + api;
Map<String, String> mHeaderParams = new HashMap<String, String>();
mHeaderParams.put("pram", "pramValue");
MultipartRequest multipartRequest = new MultipartRequest
(url, errorListener, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onUserUploadFile(response);
}
}, file, fileLength, null, mHeaderParams, partName, null);
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(
30000, //30 seconds - change to what you want
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(multipartRequest);
}
Then Call it on MainActivity:
private void test1(){
File file = new File("path:/storage/emulated/0/copy_folder/Magazine/images/assets/images/img_0007.jpg");
long fileLength = file.length();
new UserApi().uploadFile("upload", file, fileLength, "imgPost", new UserApi.UserUploadSuccessListener() {
#Override
public void onUserUploadFile(String response) {
text.setText("uploadImage() - onUserUploadFile -> \n " + response.toString());
}
#Override
public void onError(VolleyError error) {
text.setText("uploadImage() - onError -> \n " + error.toString());
}
#Override
public void onResponseError(String message) {
text.setText("uploadImage() - onResponseError -> \n " + message);
}
});
}
Here are my dependencies in Android Studio:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.google.code.gson:gson:2.3'
compile 'com.mcxiaoke.volley:library:1.0.+'
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
}

Consuming Restful WCF Service in Android

I am not sure what causing the request not to execute. I was trying to call a WCF Restful service in android, and I receive the error message "Request Error". Looking at the example, I don't see any reason why this example should not work. See below:
Here is the .Net Service:
[ServiceContract]
public interface ISampleService
{
[OperationContract]
[WebInvoke(
Method="POST", UriTemplate="/Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string Login(string value);
}
public class SampleService : ISampleService
{
public string Login(string value)
{
string t = "";
try
{
//foreach (string s in value)
//{
// t = s;
//}
return t;
}
catch (Exception e)
{
return e.ToString();
}
}
}
Java:
package com.mitch.wcfwebserviceexample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private String values ="";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)this.findViewById(R.id.btnAccess);
tv = (TextView)this.findViewById(R.id.tvAccess);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try
{
AsyncTaskExample task = new AsyncTaskExample(this);
task.execute("");
String test = values;
tv.setText(values);
} catch(Exception e)
{
Log.e("Click Exception ", e.getMessage());
}
}
public class AsyncTaskExample extends AsyncTask<String, Void,String>
{
private String Result="";
//private final static String SERVICE_URI = "http://10.0.2.2:8889";
private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
private MainActivity host;
public AsyncTaskExample(MainActivity host)
{
this.host = host;
}
public String GetSEssion(String URL)
{
boolean isValid = true;
if(isValid)
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/Login");
try
{
List<NameValuePair> value = new ArrayList<NameValuePair>(1);
value.add(new BasicNameValuePair("value", "123456"));
post.setEntity(new UrlEncodedFormEntity(value));
HttpResponse response = client.execute(post) ;
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line ="";
while((line = rd.readLine()) != null)
{
System.out.println(line);
}
}catch(Exception e)
{
Log.e("Error", e.getMessage());
}
}
return Result;
}
#Override
protected String doInBackground(String... arg0) {
android.os.Debug.waitForDebugger();
String t = GetSEssion(SERVICE_URI);
return t;
}
#Override
protected void onPostExecute(String result) {
// host.values = Result;
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.
Section1: Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)
String[][] Array = {
new String[]{"Example", "Test"},
new String[]{"Example", "Test"},
};
JSONArray jar1 = new JSONArray();
jar1.put(0, Array);
// Did not work
Section 2: The way I did it after long hours of trying and some very helpful tips and hints from #vorrtex.
**JSONArray jar1 = new JSONArray();
jar1.put(0, "ABC");
jar1.put(1, "Son");
jar1.put(2, "Niece");**
**JSONArray jarr = new JSONArray();
jarr.put(0, jar1);**
JSONArray j = new JSONArray();
j.put(0,"session");
JSONObject obj = new JSONObject();
obj.put("value", jarr);
obj.put("test", j);
obj.put("name","myName");
Log.d("Obj.ToString message: ",obj.toString());
StringEntity entity = new StringEntity(obj.toString());
Looking at the web service, and it has exactly what I was looking for.
Thanks for you help!!!!

Categories