Update Android app with HttpClient to OKHttp3 - java

I'm trying to upgrade some Java code to fit in with an android app.
The code references the depreciated the Apache http module which Android no longer supports since Marshmellow.
I need to complete a POST of the XML code.
I'm new to connections and OKHttp3. Is there a way I can achieve a similar result with using OKHttp3?
private static String SubmitXml(String Xml, String Url) throws Exception {
HttpClient client = new DefaultHttpClient();
// Prepare the POST request
HttpPost pxpayRequest = new HttpPost(Url);
pxpayRequest.setEntity(new StringEntity(Xml));
// Execute the request and extract the response
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(pxpayRequest, responseHandler);
return responseBody;
}
I've searched the web but most OKHttp3 articles I've seen reference sending JSON data or something similar. Nothing with XML.

Related

Modifying Sharepoint List From External Web Application REST API

I am attempting to modify items in a Sharepoint list using the Sharepoint REST API from back-end java code. I am using NTLM authentication to access the server and Apache httpclient to perform the http requests. I am able to perform a GET request to the list URL without issue, but when doing a POST request, I am receiving an error:
The type SP.ListItemEntityCollection does not support HTTP PATCH
method
Here is the relevant code for the POST request:
JsonObject type = new JsonObject();
type.addProperty("type", "SP.Data.MyListListItem");
JsonObject listJson2 = new JsonObject();
listJson2.add("__metadata", type);
listJson2.addProperty("Title", "test");
String backToString = listJson2.toString();
CloseableHttpClient httpClient2 = HttpClients.createDefault();
HttpPost httpPost2 = new HttpPost(LIST_URL);
httpPost2.setEntity(new StringEntity(backToString));
httpPost2.addHeader("X-RequestDigest", formDigestValue);
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("X-HTTP-Method", "MERGE");
httpPost2.addHeader("IF_MATCH", "*");
CloseableHttpResponse response2 = httpClient2.execute(httpPost2, context);
Am I doing something wrong here? I am following the post request from https://dev.office.com/sharepoint/docs/sp-add-ins/working-with-lists-and-list-items-with-rest.

How to use Twitter REST API with Java?

I am trying to use the Twitter REST API to get the trending topics from Twitter. I tried Simplest Java example retrieving user_timeline with twitter API version 1.1 but I couldn't make it to work because the HttpClient class is abstract in the newer versions of apache.
So, basically, I have no idea how to use the API based on the documentation on dev.twitter. The only thing I have achieved is to post a tweet using twitter4j, but it has no way to get Trending topics by itself.
I've also seen a lot of tutorials and how-to's but they seem to be outdated and nothing works!
Check Apache HttpClient 4.5 tutorial here
Simple Get request looks like ;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
Implement twitter api on top of it.
Edit:
HttpClient has this execute function;
#Override
public CloseableHttpResponse execute(
final HttpUriRequest request) throws IOException, ClientProtocolException {
return execute(request, (HttpContext) null);
}
which takes HttpUriRequest interface (implemented by abstract HttpRequestBase and also by HttpGet)

How to use the Android Apache HttpDelete class with parameter

I need to send an ID to the server and have the server to delete one record in a DB.
I want to use the HttpDelete Apache Android SDK integrated class but I cannot figure out how to use it and how to pass parameters to the server.
With the POST request I use .setEntity method on the HttpPost class.
But in HttpDelete there's no .setEntity method.
What I have so far achieved is:
HttpClient httpclient = new DefaultHttpClient();
HttpDelete httpdelete = new HttpDelete(url);
httpdelete.setHeader(HTTP.CONTENT_TYPE, "text/xml");
response = httpclient.execute(httpdelete);
HTTP DELETE requests do not have a body. You pass parameters right on the URL:
String url = "http://foo.com/bar?bing=bang"
HttpDelete httpdelete = new HttpDelete(url);

Android HTTP POST download manager

In android, i have this URL to which i must do a POST request
the returned inputstream of said request returns a downloadable object...
How can I use the Android Downloadmanager itself, or a custom created one, to handle the downloading process for me?
the android's Download manager is quite simple :
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse("http://www.theeUrl.fake/image.png"));
enqueue = dm.enqueue(request);
you can easily add parameter as its a GET request. I don't know if you can make a POST request from it.
EDIT : to make a post request you can use an HttpClient like this :
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
Dictionary<String, String> postFields = new Dictionary<String, String>();
// Set the post fields
postFields.add("username","toto")));
postFields.add("password", "thePassword45155")));
post.setEntity(new UrlEncodedFormEntity(postFields, HTTP.UTF_8));
// Execute the POST request
response = client.execute(post);
you should be able to get an inputstream from the httpResponse to download the file.
but you'll have to manage display / notification / cancellation... yourself.
http://ootooban.com/en/2012/custom-download-manager-for-android-2-1-part2-resumable-downloads/
Creating your own notification ontop of a post request, combined with a setProgress() & progressbar did the trick, so there is no conclusive way of using the DownloadManager sadly enough

Android Rest Client

I found so many samples for requesting a REST API, but all together are confusing, can some one please explain me a way to use http requests.
My Requirement is, I want to get data from a REST API by providing username, pwd and a key.
What I have Used was,
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("REST API url");
post.setHeader("Content-type", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "un");
obj.put("pwd", "password");
obj.put("key","123456");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
But the response is always null and these working fine when tested with browser tool by posting the same data.Is some thing wrong with my approach? please suggest me the correct way. Thank you
(1) Google I/O video session for developing REST clients
(2) search in android developer blog
(3) https://github.com/darko1002001/android-rest-client
Please try after that post your question,
I can share code snippet from my rest client developed based on (1) & (2)
Do not use Cloud to Device Messaging, instead use the latest cloud approach with android application development.
There is new library called Volley, which looks better than AsyncTask. It should be useful in developing RESTful clients.
You probably forgot to add the internet permission to the manifest file.
Add the following line.
<uses-permission android:name="android.permission.INTERNET" />
I thing you should try this,
HttpContext localContext = new BasicHttpContext();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("REST API url");
post.setHeader("Content-type", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "un");
obj.put("pwd", "password");
obj.put("key","123456");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post,localContext);
Hope this will help.
By any chance, is the server expecting a GET request for this operation? If so, you may want to use HttpGet instead of HttpPost.

Categories