Android HttpPost and HttpClient Substitute - http-post

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

Related

Upgrade code from org.eclipse.jetty.websocket.websocket-client to org.eclipse.jetty.websocket.websocket-jakarta-client

I have the following application code in an application that I would like to migrate to Spring3 in order to do so javax is replaced with jakarta.
Any one have any Idea how to migrate the following code:
// Let's create and start the Web Socket
//
// For internal test, we have a self-signed certificate. So we need to short cut certificate check.
// DO NOT DO THAT IN PRODUCTION!
boolean trustAll = (System.getProperty("com.graphql-java-generator.websocket.nosslcheck") != null);
org.eclipse.jetty.util.ssl.SslContextFactory.Client sslContextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory.Client(
trustAll);
org.eclipse.jetty.client.HttpClient httpClient = new HttpClient(sslContextFactory);
org.eclipse.jetty.websocket.client.WebSocketClient wsClient = new WebSocketClient(httpClient);
SubscriptionClientWebSocket<R, T> subscriptionClientWebSocket = new SubscriptionClientWebSocket<R, T>(request,
subscriptionName, subscriptionCallback, subscriptionType, messageType,
graphQLRequest.getGraphQLObjectMapper());
URI uri = getWebSocketURI();
try {
wsClient.start();
org.eclipse.jetty.websocket.client.ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest();
wsClient.connect(subscriptionClientWebSocket, uri, clientUpgradeRequest);
logger.debug("Connecting to {}", uri);
} catch (Exception e) {
String msg = "Error while opening the Web Socket connection to " + uri;
logger.error(msg);
throw new GraphQLRequestExecutionException(msg, e);
}
Having not found any documentation on how to proceed with this migration.
Tried using the JakartaWebSocketClientContainer but could not find how to use with an UpgradeRequest
Your code is not using javax.websocket, so there's nothing to upgrade.
The techniques you are using in your code to manage the SSL behavior is also not possible in either javax.websocket or jakarta.websocket (There is no API you can use to manage SSL/TLS in those)

How to get the status code of a website

I wanna get the status code of "www.google.com" by these codes:
final HttpClient client = new DefaultHttpClient();
final HttpPost method = new HttpPost("http://www.google.com");
try {
HttpResponse response = client.execute(method);
int code = response.getStatusLine().getStatusCode();
Log.i("LOG", "Code : " + code);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
but it gives me the code "405" means we have a problem.
what's the problem with this code?
give me another code to do the same job.but please a simple code. I'm a begginer :)
By the way
I've heard httpclient is deprecated.
I do not believe www.google.com let's you do a POST. That end-point likely only accepts GET requests.
Try googling for a website that accepts dumpy posts. Or standup a test website that accepts POSTs. That should be pretty easy using node.js.

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?

MultipartEntityBuilder setMode() not working

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

Sending gzipped data over HTTPS

I need to send a gzipped byte array over HTTPS. I searched the web and only thing ı can found is SharpGIS.GZipWebClient.
However, the problem is - this third party solution only works with WebClient which allow you to send only String data.
(I'm on Windows Phone 8. Most of the WebClient methods do not exist.)
Any ideas to solve this problem?
Edit:
This is how I tried the POST JSON data over HTTPS using SharpGIS;
WebClient webClient = new SharpGIS.GZipWebClient();
webClient.Headers["Accept-Encoding"] = "gzip";
var uri = new Uri(pUrl, UriKind.Absolute);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
webClient.UploadStringTaskAsync(uri, jsonAsString);
But it doesn't compresses the string as well(as using OpenWriteSync method).
You write the post data in the OpenWriteCompleted handler, like this:
void webClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
Stream s = e.Result;
s.Write(jsonAsByteArray, 0, jsonAsByteArray.Length);
s.Flush();
s.Close();
}
You should also add the appropriate error handling.

Resources