MultipartEntityBuilder setMode() not working - apache-httpcomponents

Using apache httpcomponents-client-4.3.6-bin libs.
This code is producing an HttpEntity intance with both parts containing the Content-Tranfer-Encoding header. I can't eliminate these headers using setMode(HttpMultipartMode.BROWSER_COMPATIBLE) or setLaxMode(). Does anyone have any suggestions please?
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
List<ContentType> contentTypeList = new ArrayList<>();
contentTypeList.add(ContentType.create("application/x-dmas+json"));
contentTypeList.add(ContentType.create("application/exe"));
int idx = 0;
while(paramKeysIt.hasNext()) {
builder.addBinaryBody(key = paramKeysIt.next(), params.get(key), contentTypeList.get(idx++), params.get(key).getName());
}
HttpEntity reqEntity = builder.build();

Very strange. By POSTing my request to an echo server I am able to see that the Content-Transfer-Encoding headers are indeed absent, even though they show up clearly, and repeatedly in the debugger!
Using NetBeans IDE 8.0

Related

Porting JSONObject (Android) to JObject (JSON.NET)

I have some native android code which receives data back from the server which is then added to a JSONObject for later manipulation.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd();
JSONObject responseObj = new JSONObject(responseStr);
However, I'm moving this over to an mvvm framework so JSONObject can't be used (I'm also happier working with the much nicer JSON.NET libraries).
I've changed the JSONObject to JObject and come up with the following which compiles, but throws an exception on running (Cannot add a jtoken to a object)
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd();
var responseObj = new JObject(responseStr);
From what I've read, this should work (but is obviously isn't). Is there a way to store the responseStr as a JObject?
use JObject.Parse
var responseObj = new JObject.Parse(responseStr);

SOAP in SWIFT import a Objective C Class

Hi I'm gonna code my application on xCode in Swift, before i had problems with my WebService SOAP in Android, so I did some search and they're a lot of subjects about, but my WebService is particular, look in Android what I did:
SSLConnection.allowAllSSL();
SoapObject request = new SoapObject(NAMESPACE, "SendLead");
request.addProperty("xml", xml);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportBasicAuth httpTransport = new HttpTransportBasicAuth(URL, getResources().getString(R.string.login), getResources().getString(R.string.mdp));
httpTransport.debug = true;
httpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
Log.i(TAG, "Result Celsius: " + result);
SoapObject SendLeadReturn = (SoapObject) result.getProperty("SendLeadReturn");
String code = SendLeadReturn.getPropertyAsString("code");
So I have many constrains:
https URL
I have to keep my login to use the other functions of the wsdl (HttpTransportBasicAuth)
I send and receive xml strings
How to do it, I think it's preferable to import a Objective C class, but which and how please ?

How do I replace an existing Community file on IBM SmartCloud

I am trying to replace an existing Community file using the following java
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("createVersion", "false");
fileEntry = fileService.updateCommunityFile(fis, fileUuid, fileName, communityLibraryId, paramsMap);
But it is returning a HTTP 411:Length required error.
I am using the latest build (1.1.5.20150520-1200.jar)
Does anyone have a suggestion as to what i am missing?
I tried recreating the issue but I am able to upload New version of Community file correctly with and without version, using the updateCommunityFile API. I do not get any Length related error. This is the snippet I am using :
java.io.File file = new java.io.File("C://TestUploadCommunity.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (Exception e) {
//TODO
}
fileEntry = fileService.updateCommunityFile(fis, fileEntry.getFileId(), fileEntry.getLabel(), communityLibraryId, params);
Can you share more details on your sample, what exactly is your fis?
I have tried this on 2 environments and I do not see any issue.
Also, from the entry you have pasted,
"Request to url apps.na.collabserv.com/files/basic/api/library... /document/... /entry?content-length=6600&createVersion=false returned an error response 411:Length Required HTTP/1.1 411"
It seems that somehow an incorrect content-length is passed for your request.
Can you share the sample that you are using?

Android HttpPost and HttpClient Substitute

Just a quick question.
Until now I have been using HttpClient and HttpPost to post a file and some parameters to a php script on my server.
However they have been deprecated.
I was wondering what i could use to substitute it.
I found some answers on other posts but unfortunately i didn't manage to integrate any of them with the HttpMime Library that i am using for a MultiPartEntity post.
HttpClient httpclient = new DefaultHttpClient(); // Deprecated
HttpPost httpost = new HttpPost(inData[0].URL); // Deprecated
// Request To Entity
MultipartEntity entity = new MultipartEntity();
// Add Parameters
for(Request r : inData[0].Params)
entity.addPart(r.Key, new StringBody(r.Body));
// Add File
entity.addPart("img", new FileBody(inData[0].FileToUpload));
httpost.setEntity(entity);
HttpResponse responsePOST = httpclient.execute(httpost); // Deprecated
HttpEntity resEntity = responsePOST.getEntity(); // Deprecated
if (resEntity != null)
inData[0].RequestResult.add(EntityUtils.toString(resEntity));
else
throw new Exception("");
return inData[0];
} catch (Exception e) {
e.printStackTrace();
inData[0].RequestResult.add("ERROR");
}
return inData[0];
Would anyone point me in the right direction? Thanks
At my job we also used the apache libraries but we have replaced them with okHTTP.
More information about okHTTP can be found here: http://square.github.io/okhttp/
Information about uploading multipart files can be found here:
Uploading a large file in multipart using OkHttp

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

Resources