the request was rejected because no multipart boundary was found when creating new document in Docushare Flex - spring-boot

I am trying to create new document in Docushare Flex using new docushare rest api and my request body suppose to be XML and I am generating it with requested data, when I send the request I get this error "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml(filePath, parentId, documentTitle, fileName, ownerId);
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
StringEntity bodyEntity = new StringEntity(createDocumentXml, ContentType.MULTIPART_FORM_DATA);
request.setEntity(bodyEntity);
CloseableHttpResponse response = client.execute(request);
System.out.println("Status is " + response.getStatusLine());
HttpEntity entity = response.getEntity();

I have used this block of code to upload a document in DocuShare Flex
HttpPost request = new HttpPost(postUrl);
String filePath = "C:/Test/CreateDocument.xml";
String createObj = helper.createDocumentXml();
String createDocumentXml= null;
{
try {
createDocumentXml = FileUtils.readFileToString(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
FileBody body = new FileBody(file.toFile());
StringBody xmlContent = new StringBody(createDocumentXml, ContentType.APPLICATION_XML);
String boundry = UUID.nameUUIDFromBytes(file.toString().getBytes()).toString();
HttpEntity entity = MultipartEntityBuilder.create()
.setBoundary(boundry)
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)`enter code here`
.addPart("content", body)
.addPart("request", xmlContent)
.build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();

Related

Sinch java error

i am using sinch from java, i recently reput credit to the account, and now when i try to send message i get succes message, but the sms isn't send. Following the link https://messagingapi.sinch.com/v1/sms/162393899 i get this
{"errorCode":40107,"message":"Invalid authorization key:
vivi******#gmail.com","reference":"BA:vivi******#gmail.com_GtIfKPDMJEKL4VJWR0kkJQ"}
the code
try {
String phoneNumber = "+40732******";
String appKey = "*****";
String appSecret = "****";
String message = "Test";
URL url = new URL("https://messagingapi.sinch.com/v1/sms/" + phoneNumber);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String userCredentials = "application\\" + appKey + ":" + appSecret;
byte[] encoded = Base64.encodeBase64(userCredentials.getBytes());
String basicAuth = "Basic " + new String(encoded);
connection.setRequestProperty("Authorization", basicAuth);
String postData = "{\"Message\":\"" + message + "\"}";
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder response = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
}

Get document from GET request

I need your help:
I have the following method
#Path("/download")
public class FileDownloadService {
#GET
public Response downloadFile(#QueryParam("filenet_id") String filenet_id, #QueryParam("version") String version) {
...
Document document = (Document) cmisObject;
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
}
and I want to get the document throught HTTP GET, I tried to write this code but I don't know how to get it, "output" don't conatains it:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("localhost:8080").setPath("/filenetintegration/rest/download")
.setParameter("filenet_id", filenet_id)
.setParameter("version", version+".0");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
HttpURLConnection urlConnection = (HttpURLConnection) new URL(uri.toString()).openConnection();
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
Edit:
maybe the problem is on this line, it don't put the document inside the response:
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
You need something like this on the server side:
Document document = (Document) cmisObject;
ContentStream contentStream = document.getContentStream();
final InputStream stream = contentStream.getStream();
StreamingOutput output = (OutputStream out) -> {
try {
int b;
byte[] buffer = new byte[64*1024];
while ((b = stream.read(buffer)) > -1) {
out.write(buffer, 0, b);
}
} finally {
try {
stream.close();
} catch (IOException ioe) {}
}
};
return Response.ok(output, contentStream.getMimeType()).build();

loopj JsonObject with inside JsonArray JsonObjects

I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android

MVC 3 GET Webservice and Response

I'm attempting to build a GET webservice that would from website 1 initiate a GET request...sending that request to website 2 and website two would respond by sending a list of objects. I using Json.net to serialize and deserialize the List of objects.
I've put together a POST webservice with the assistance of this question.. WebService ASP.NET MVC 3 Send and Receive
But I've been unsuccessful so far at adapting that example for my new requirement.
Here is what I have so far from website 1..
public static List<ScientificFocusArea> ScientificFocusAreas()
{
string apiURL = "http://localhost:50328/Api/GetAPI";
//Make the post
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
//var bytes = Encoding.Default.GetBytes(body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
Stream stream = null;
try
{
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = -1;
request.Method = "GET";
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
List<ScientificFocusArea> listSFA = WebService.GetResponse_ScientificFocusArea(request);
return listSFA;
}
public static List<ScientificFocusArea> GetResponse_ScientificFocusArea(HttpWebRequest request)
{
List<ScientificFocusArea> listSFA = new List<ScientificFocusArea>();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var end = string.Empty;
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
listSFA = JsonConvert.DeserializeObject<List<ScientificFocusArea>>(end);
}
response.Close();
}
}
return listSFA;
}
Then on the website 2...
public class GetAPIController : Controller
{
//
// GET: /Api/GetAPI/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetScientificFocusAreas()
{
//Get list of SFAs
List<ScientificFocusArea> ListSFA = CreateList.ScientificFocusArea();
string json = JsonConvert.SerializeObject(ListSFA, Formatting.Indented);
//Send the the seralized object.
return Json(json);
}
}
Also, on website 2, I've registered this route for the incoming request...
context.MapRoute(
"GetScientificFocusAreas",
"Api/GetAPI/",
new
{
controller = "GetAPI",
action = "GetScientificFocusAreas",
id = UrlParameter.Optional
}
);
I'm currently getting the error.. he remote server returned an error: (404) Not Found.
Any help would me greatly appreciated.
The problem seems like a routing issue. I would start with the RouteDebugger which can be found here. This tool gives insight into which routes your URL is hitting.
The code I use for a HTTP GET is a bit different that what you have above. It's included below.
public T Get<T>(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var end = string.Empty;
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
response.Close();
JsonSerializer serializer = new JsonSerializer();
serializer.Binder = new DefaultSerializationBinder();
JsonReader jsonReader = new JsonTextReader(new StringReader(end));
T deserialize = serializer.Deserialize<T>(jsonReader);
return deserialize;
}
}
catch (Exception ex)
{
throw new ApiException(string.Format("An error occured while trying to contact the API. URL: {0}", url), ex);
}
}
The other issue I see is in the GetScientificFocusAreas() method. On the second line of the code the objects are converted to JSON. Which is fine, but the last line of code the json is passed into the Json() method. Which converts the string into Json yet again. When using the JSON.Net library use the Content() method in the return instead of Json() and set the content type to application/json
The reasoning for using an external Json converter rather than the internal converter is simply the internal json converter has a few known issues. JSON.Net has been around for years and is solid.

how to perform post method in windows 8 metro?

I have followed the HttpClient samples but couldn't figure it out how to post a method with 2 parameters.
Below is what I tried but it return bad gateway error:
private async void Scenario3Start_Click(object sender, RoutedEventArgs e)
{
if (!TryUpdateBaseAddress())
{
return;
}
Scenario3Reset();
Scenario3OutputText.Text += "In progress";
string resourceAddress = "http://music.api.com/api/search_tracks";
try
{
MultipartFormDataContent form = new MultipartFormDataContent();
// form.Add(new StringContent(Scenario3PostText.Text), "data");
form.Add(new StringContent("Beautiful"), "track");
form.Add(new StringContent("Enimem"), "artist");
HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form);
}
catch (HttpRequestException hre)
{
Scenario3OutputText.Text = hre.ToString();
}
catch (Exception ex)
{
// For debugging
Scenario3OutputText.Text = ex.ToString();
}
}
I looked all over the internet, but couldn't find any working examples or documents that show how to perform the http post method. Any materials or samples would help me a lot.
Try FormUrlEncodedContent instead of MultipartFormDataContent:
var content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("track", "Beautiful"),
new KeyValuePair<string, string>("artist", "Enimem")
}
);
I prefer to take the following approach where you set the POST data into the request content body. Having to debug it is much easier!
Create your HttpClient object with the URL you're posting to:
string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();
Form your request with the Post method to your url
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl);
Create a content string with your parameters explicitly set in POST data format and set these in the request:
string content = "track=beautiful" +
"&artist=eminem"+
"&rating=explicit";
request.Method = HttpMethod.Post;
request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
Send the request and get a response:
try
{
HttpResponseMessage response = await theAuthClient.SendAsync(request);
handleResponse(response);
}
catch (HttpRequestException hre)
{
}
Your handler will be called once the request returns and will have response data from your POST. The following example shows a handler that you could put a breakpoint into to see what the response content is, at that point, you could parse it or do whatever you need to do with it.
public async void handleResponse(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
if (content != null)
{
// put your breakpoint here and poke around in the data
}
}

Resources