I want to store these values to server.
The data which i have to store is complete in the variables.
I should get
{"response":{"result":1,"Message":"Poll Entered Successfully."}}
from server
but getting -1
#Override
protected String doInBackground(String... params) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
String squestion = question.getText().toString();
String shashtag = hashTag.getText().toString();
spolltime = polltime.getText().toString();
StringBuilder scat = new StringBuilder();
scat.append("");
scat.append(categoryid);
StringBuilder sid = new StringBuilder();
sid.append("");
sid.append(LoginPage.logid);
//int ipolltime = Integer.parseInt(spolltime);
String equestion = URLEncoder.encode(squestion,"UTF-8");
String ehashtag = URLEncoder.encode(shashtag,"UTF-8");
String ecategory = URLEncoder.encode(scat.toString(),"UTF-8");
String eA = URLEncoder.encode(OptionA.stext,"UTF-8");
String eB = URLEncoder.encode(OptionB.stext,"UTF-8");
String eC = URLEncoder.encode(OptionC.stext,"UTF-8");
String eD = URLEncoder.encode(OptionD.stext,"UTF-8");
String eid = URLEncoder.encode(sid.toString(),"UTF-8");
String epolltime = URLEncoder.encode(spolltime,"UTF-8");
URL linkurl = new URL("http://iipacademy.in/askpoll/pollfeeds.php?user_id="+eid+"&question="+equestion+
"&hashtag="+ehashtag+"&category_id="+ecategory+"&option1="+eA+"&option2="+eB+"&option3="+eC+"&option4="+eD+"" +
"&pollopen="+epolltime+"&optiontype1=texty&optiontype2=texty&optiontype3=texty&optiontype4=texty");
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
//Toast.makeText(getApplicationContext(),jsonString.toString(),
//Toast.LENGTH_LONG).show();
return jsonString;
}
I am not able to find my mistake !
thanks
first of all try to make this call from browser and check for response . there is an extension
on chrome PostMan rest client. please check first. may be you are not getting the response correctly.
Related
How to upload a video to a particular YouTube account from my android app i have followed https://github.com/youtube/yt-direct-lite-android but its not very documented.
I have tried
public class YoutubeUploader {
private static final String TAG = "YoutubeUploader";
// After creating project at http://www.appspot.com DEFAULT_YTD_DOMAIN == <Developers Console Project ID>.appspot.com [ You can find from Project -> Administration -> Application settings]
//public static final String DEFAULT_YTD_DOMAIN = "developerconsolid.appspot.com";
// I used Google APIs Console Project Title as Domain name:
//public static final String DEFAULT_YTD_DOMAIN_NAME = "Domain Name";
//From Google Developer Console from same project (Created by SHA1; project package)
//Example https://console.developers.google.com/project/apps~gtl-android-youtube-test/apiui/credential
public static final String DEVELOPER_KEY = "<MY_DEVELOPER_KEY>";
// CLIENT_ID == Google APIs Console Project Number:
public static final String CLIENT_ID = "157613";
public static final String YOUTUBE_AUTH_TOKEN_TYPE = "youtube";
private static final String AUTH_URL = "https://www.google.com/accounts/ClientLogin";
// Uploader's user-name and password
private static final String USER_NAME = "my#gmail.com";
private static final String PASSWORD = "mypassword";
private static final String INITIAL_UPLOAD_URL = "https://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads";
private static String getClientAuthToken() {
try {
URL url = new URL(AUTH_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String template = "Email=%s&Passwd=%s&service=%s&source=%s";
String userName = USER_NAME; // TODO
String password = PASSWORD; // TODO
String service = YOUTUBE_AUTH_TOKEN_TYPE;
String source = CLIENT_ID;
userName = URLEncoder.encode(userName, "UTF-8");
password = URLEncoder.encode(password, "UTF-8");
String loginData = String.format(template, userName, password, service, source);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outStreamWriter.write(loginData);
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200) {
Log.d(TAG, "Got an error response : " + responseCode + " " + urlConnection.getResponseMessage());
throw new IOException(urlConnection.getResponseMessage());
} else {
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("Auth=")) {
String split[] = line.split("=");
String token = split[1];
Log.d(TAG, "Auth Token : " + token);
return token;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String upload(YoutubeUploadRequest uploadRequest, ProgressListner listner, Activity activity) {
totalBytesUploaded = 0;
String authToken = getClientAuthToken();
if(authToken != null) {
String uploadUrl = uploadMetaData(uploadRequest, authToken, activity, true);
File file = getFileFromUri(uploadRequest.getUri(), activity);
long currentFileSize = file.length();
int uploadChunk = 1024 * 1024 * 3; // 3MB
int start = 0;
int end = -1;
String videoId = null;
double fileSize = currentFileSize;
while (fileSize > 0) {
if (fileSize - uploadChunk > 0) {
end = start + uploadChunk - 1;
} else {
end = start + (int) fileSize - 1;
}
Log.d(TAG, String.format("start=%s end=%s total=%s", start, end, file.length()));
try {
videoId = gdataUpload(file, uploadUrl, start, end, authToken, listner);
fileSize -= uploadChunk;
start = end + 1;
} catch (IOException e) {
Log.d(TAG,"Error during upload : " + e.getMessage());
}
}
if (videoId != null) {
return videoId;
}
}
return null;
}
public static int totalBytesUploaded = 0;
#SuppressLint("DefaultLocale")
#SuppressWarnings("resource")
private static String gdataUpload(File file, String uploadUrl, int start, int end, String clientLoginToken, ProgressListner listner) throws IOException {
int chunk = end - start + 1;
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
FileInputStream fileStream = new FileInputStream(file);
URL url = new URL(uploadUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
urlConnection.setRequestProperty("GData-Version", "2");
urlConnection.setRequestProperty("X-GData-Client", CLIENT_ID);
urlConnection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
// some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(chunk);
urlConnection.setRequestProperty("Content-Type", "video/3gpp");
urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end,
file.length()));
Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));
OutputStream outStreamWriter = urlConnection.getOutputStream();
fileStream.skip(start);
double currentFileSize = file.length();
int bytesRead;
int totalRead = 0;
while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
outStreamWriter.write(buffer, 0, bytesRead);
totalRead += bytesRead;
totalBytesUploaded += bytesRead;
double percent = (totalBytesUploaded / currentFileSize) * 100;
if(listner != null){
listner.onUploadProgressUpdate((int) percent);
}
System.out.println("GTL You tube upload progress: " + percent + "%");
/*
Log.d(LOG_TAG, String.format(
"fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
totalBytesUploaded, percent));
*/
//dialog.setProgress((int) percent);
// TODO My settings
if (totalRead == (end - start + 1)) {
break;
}
}
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "responseCode=" + responseCode);
Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());
try {
if (responseCode == 201) {
String videoId = parseVideoId(urlConnection.getInputStream());
return videoId;
} else if (responseCode == 200) {
Set<String> keySet = urlConnection.getHeaderFields().keySet();
String keys = urlConnection.getHeaderFields().keySet().toString();
Log.d(TAG, String.format("Headers keys %s.", keys));
for (String key : keySet) {
Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
}
Log.w(TAG, "Received 200 response during resumable uploading");
throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
if ((responseCode + "").startsWith("5")) {
String error = String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage());
Log.w(TAG, error);
// TODO - this exception will trigger retry mechanism to kick in
// TODO - even though it should not, consider introducing a new type so
// TODO - resume does not kick in upon 5xx
throw new IOException(error);
} else if (responseCode == 308) {
// OK, the chunk completed succesfully
Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
// TODO - this case is not handled properly yet
Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
urlConnection.getResponseMessage(), uploadUrl));
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
private static String parseVideoId(InputStream atomDataStream) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(atomDataStream);
NodeList nodes = doc.getElementsByTagNameNS("*", "*");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String nodeName = node.getNodeName();
if (nodeName != null && nodeName.equals("yt:videoid")) {
return node.getFirstChild().getNodeValue();
}
}
return null;
}
private static File getFileFromUri(Uri uri, Activity activity) {
try {
String filePath = null;
String[] proj = { Video.VideoColumns.DATA };
Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(Video.VideoColumns.DATA);
filePath = cursor.getString(column_index);
}
cursor.close();
//String filePath = cursor.getString(cursor.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String uploadMetaData(YoutubeUploadRequest uploadRequest, String clientLoginToken, Activity activity, boolean retry) {
try {
File file = getFileFromUri(uploadRequest.getUri(), activity);
if(file != null) {
String uploadUrl = INITIAL_UPLOAD_URL;
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
connection.setRequestProperty("GData-Version", "2");
connection.setRequestProperty("X-GData-Client", CLIENT_ID);
connection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/atom+xml");
connection.setRequestProperty("Slug", file.getAbsolutePath());
String title = uploadRequest.getTitle();
String description = uploadRequest.getDescription();
String category = uploadRequest.getCategory();
String tags = uploadRequest.getTags();
String template = readFile(activity, R.raw.gdata).toString();
String atomData = String.format(template, title, description, category, tags);
/*String template = readFile(activity, R.raw.gdata_geo).toString();
atomData = String.format(template, title, description, category, tags,
videoLocation.getLatitude(), videoLocation.getLongitude());*/
OutputStreamWriter outStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outStreamWriter.write(atomData);
outStreamWriter.close();
int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode >= 300) {
// The response code is 40X
if ((responseCode + "").startsWith("4") && retry) {
Log.d(TAG, "retrying to fetch auth token for ");
clientLoginToken = getClientAuthToken();
// Try again with fresh token
return uploadMetaData(uploadRequest, clientLoginToken, activity, false);
} else {
return null;
}
}
return connection.getHeaderField("Location");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static CharSequence readFile(Activity activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
// Chomp the last newline
buffer.deleteCharAt(buffer.length() - 1);
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
/**
* Closes the specified stream.
*
* #param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
public static interface ProgressListner {
void onUploadProgressUpdate(int progress);
}
I am getting 404 error in getClientAuthToken() method.I think "https://www.google.com/accounts/ClientLogin";deprecated by google any alternative to this
plz help me
I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask
my Update code doesn't execute.
in this line my update calss doesnt run
dataupdate.execute();
CODE:
public class Update extends AsyncTask<Void, Void, Integer> {
private String User;
private final String mLink;
public Update(String user) {
User = user;
mLink = "http://www./Update.php";
}
#Override
protected Integer doInBackground(Void... params) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
}
return null;
}
}
Main:
showProgress(true);
dataupdate = new Update(username);
dataupdate.execute();
// dataupdate.execute((Void) null);
showProgress(false);
do it like this
public class Update extends AsyncTask<String, String, Integer> {
#Override
protected Integer doInBackground(String... params) {
User user=params[0]; //get string user value here
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(user, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
to run
//put username value in execute
new Update()execute(username);
I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.
send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this
Android code
public String postFiless( byte[] imgbyt, String urlString) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
byte[] data = imgbyt;
String fileName = String.format("File_%d.jpg",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
builder.addPart("image", bab);
final HttpEntity entity = builder.build();
post.setEntity(entity );
HttpResponse response = client.execute(post);
Log.e("result code", ""+response.getStatusLine().getStatusCode());
return getContent(response);
}
public static String getContent(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null)
{
content += body + "\n";
}
return content.trim();
}
WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID
Three steps to upload image using Multipart Parser from android to WCF Rest Service
//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream) {
string strRet = string.Empty;
string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
try {
MultipartParser parser = new MultipartParser(fileStream);
if (parser.Success) {
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
Encoding encoding = Encoding.UTF8;
FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
fileStream.Close();
strRet= fileName;
} else {
return "Image Not Uploaded";
} }
catch (Exception ex) {
// handle the error
}
return strRet;
}
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser {
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
public MultipartParser(Stream stream) {
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding) {
this.Parse(stream, encoding);
}
public string getcontent(Stream stream, Encoding encoding) {
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in sections) {
Match nameMatch = new Regex(#"(?<=name\=\"")(.*?)(?=\"")").Match(s);
string name = nameMatch.Value.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(name)) {
int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
}
}
string strRet = ""; //Parameters["name"];
return strRet;
}
private void Parse(Stream stream, Encoding encoding) {
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1) {
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
//re = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
//Match nameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success) {
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true; }
} }
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex) {
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1) {
while ((startPos + index) < searchWithin.Length) {
if (searchWithin[startPos + index] == serachFor[index]) {
index++;
if (index == serachFor.Length) {
return startPos;
}
} else {
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1) {
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream) {
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream()) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success {
get;
private set;
}
public string ContentType {
get;
private set;
}
public string Filename {
get;
private set;
}
public byte[] FileContents {
get;
private set;
}
public string Imgname {
get;
private set;
} }
// End of Wcf rest Service Code
Android to WCF: Streaming multi part image and Json string
I want to create a WCF-RESTful web service method,in which i need to upload an image(multipart-form data) along with some other information (in JSON format). This web service will be accessed by android and iPhone application to send Image and json information as
I want WCF Server Side and Android Code, Help me
I'm trying to upload an image and a text to a wcf service. I create a service to save upload images:
Rest Client Code
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
MemoryStream mStream = new MemoryStream();
Bitmap bmpPostedImage = new Bitmap(FileUpload1.PostedFile.InputStream);
bmpPostedImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageArray = mStream.ToArray();
mStream.Close();
VehicleCheckListTransaction objAttachmentRequestDto = new VehicleCheckListTransaction();
objAttachmentRequestDto.VehicleCheckListTransactionID = 0;
objAttachmentRequestDto.VehicleCheckListID = 2;
objAttachmentRequestDto.TTID = 10;
objAttachmentRequestDto.UserID = 226;
objAttachmentRequestDto.UserTypeID = 4;
objAttachmentRequestDto.ValidTill = "215-05-10";
objAttachmentRequestDto.CurrentDate = "215-07-22";
objAttachmentRequestDto.CurrentStatus = "Yes";
objAttachmentRequestDto.CreatedBy= 226;
objAttachmentRequestDto.ModifiedBy = 226;
objAttachmentRequestDto.CreatedDate = string.Empty;
objAttachmentRequestDto.ModifiedDate = string.Empty;
objAttachmentRequestDto.Notes = "Some Text";
objAttachmentRequestDto.IsActive = true;
objAttachmentRequestDto.FileName = "";
objAttachmentRequestDto.FilePath = "";
objAttachmentRequestDto.VerifiedBy = 226;
var serializer = new DataContractJsonSerializer(typeof(VehicleCheckListTransaction));
var ms = new MemoryStream();
serializer.WriteObject(ms, objAttachmentRequestDto);
ms.Position = 0;
var reader = new StreamReader(ms);
string requestBody = reader.ReadToEnd();
var client = new RestClient();
client.BaseUrl = new Uri("http://localhost:49188/WDS_SERVICE.svc/");
var request = new RestRequest(Method.POST) { DateFormat = DataFormat.Json.ToString(), Resource = "vehiclechecklisttransaction/Add" };
if (requestBody != null)
request.AddParameter("VehicleCheckListTransaction", requestBody);
request.AddFile("file1", imageArray, "NEVER.jpg");
var response = client.Execute(request);
}
}
WCF Service Code
public string UploadPhoto(Stream request)
{
//Read in our Stream into a string...
StreamReader reader = new StreamReader(request);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsCustomer" record.
JavaScriptSerializer jss = new JavaScriptSerializer();
Checklist Checklist = jss.Deserialize<Checklist>(JSONdata);
try
{
FileStream targetStream = null;
Stream sourceStream = Checklist.fileContents;
String guid = Guid.NewGuid().ToString();
//get photofolder path
string photofolderName = "Trip\\Android";
string filename = guid + ".JPEG";
string uriPath = "file:\\C:\\inetpub\\wwwroot\\WDS\\Media\\" + photofolderName + "\\" + filename;
string photopath = new Uri(uriPath).LocalPath;
using (targetStream = new FileStream(photopath, FileMode.Create, FileAccess.Write, FileShare.None))
{
//read from the input stream in 6K chunks
//and save to output stream
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
db.Checklists.Add(Checklist);
db.SaveChanges();
return filename + "_" + Checklist.ChecklistID;
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
I receive data in webservice and insert in sqlite database Android but if filed is empty repeat before filed As far as new filed no empty and repeat ...
please help me:
public class gfc extends AsyncTask {
private String Link = "";
private String Count = "";
private String tid = "";
private String tim = "";
private String tuser = "";
private String tusername = "";
private String tmatn = "";
private String tcomments = "";
private String tlikes = "";
private String tdate = "";
private String tip_addr = "";
private database db;
public gfc(String link, String count, Context c) {
Link = link;
Count = count;
db = new database(c);
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data = URLEncoder.encode("count", "UTF8") + "=" + URLEncoder.encode(Count, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
db.open();
while ((line = reader.readLine()) != null) {
int f = 0;
int c = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
String temp = line.substring(f, i);
if (c == 0) {
tid = temp;
}
if (c == 1) {
tdate = temp;
}
if (c == 2) {
tuser = temp;
}
if (c == 3) {
tusername = temp;
}
if (c == 4) {
tip_addr = temp;
}
if (c == 5) {
tcomments = temp;
}
if (c == 6) {
tlikes = temp;
}
if (c == 7) {
tim = temp;
}
if (c == 8) {
tmatn = temp.replace("^", "\n");
}
c += 1;
f = i + 1;
}
}
db.insert(tid, tuser, tusername, tmatn, tcomments, tlikes, tdate, tip_addr, tim);
sb.append("t");
}
db.close();
index.res = sb.toString();
} catch (Exception e) {}
return "";
}
}