REST PUT Response format - java

I have an android application with a MySQL database. Rows entered on the android tablet need to be synchronised on a server, also with MySql. Once written onto the server the server Unique Integer needs to be returned to the tablet to update the local database. That way it will x-ref the client to the server. It currently works by performing a PUT for each row and using the location for the server ID in the response. However it takes ages if there are a significant amount of updates, inserts as each one row opens a new HttpConnection. I would like to be able to group the updates in one XML String and get an XML file returned with the xreference of the serverID for each Client ID. However I cannot find a way of sending XML in the response, only a URI. My connection code is
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, Const.HTTP_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, Const.HTTP_SOCKET_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("xxxxx","xxxxx")); // TODO Change to logged user name
HttpPut put = new HttpPut(uri);
StringEntity entity = new StringEntity(xml);
entity.setContentType("application/xml");
put.setEntity(entity);
HttpClientParams.setRedirecting(put.getParams(), false);
HttpResponse response = client.execute(put);
switch (response.getStatusLine().getStatusCode()){
case 200:
case 201:
location = response.getLastHeader("Location").getValue();
key = location.substring(location.lastIndexOf("/")+1);
break;
case 401:
throw new RuntimeException("Authorisation Failed");
default:
throw new RuntimeException("Failed to Create Data Record on Server");
}
And on the Server
if (flight.getClientFlightId()!=0){
if (insertFlight(userId)){
xref += "<clientId>"+flight.getClientFlightId()+"</clientId><serverId>"+flight.getServerFlightId()+"</serverId>";
}
}
xref +="</xref>";
response = Response.created(URI.create(xref)).build();
Anyone able to help please?

ArrayList<NameValuePair> putParams = new ArrayList<NameValuePair>();
putParams.add(new BasicNameValuePair("myXML", "<xml> _PUT_YOUR_XML_HERE_ </xml>"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(putParams);
put.setEntity(formEntity);

Related

How to write / convert CURL for Android java

I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.

How to send binary file using HttpClient approach

I am trying to send a two binary file to one of the REST API. But I get 400 bad request response from the end point.
Need to send below key and values to endpoint.
userForm - user.xml
structureForm - structure.xdp
Below is the java code, [UPDATED CODE]
HttpPost request = new HttpPost(url);
File userForm = new File("D:\\Downloads\\user.xml");
LOG.info("length ---->" + userForm.length()); // See valid file size
HttpEntity userFormEntity = MultipartEntityBuilder.create()
.addPart("userForm", new FileBody(userForm))
.build();
File structureFile = new File("D:\\Downloads\\structure.xdp");
LOG.info("length structureFile ---->" + structureFile.length()); // See valid file size
HttpEntity structureEntity = MultipartEntityBuilder.create()
.addPart("structureForm", new FileBody(structureFile))
.build();
if (userFormEntity != null && structureEntity != null) {
request.setEntity(userFormEntity);
request.setEntity(structureEntity);
}
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(request);
Seemed like the key 'userForm' and 'structureForm' are not going properly to end point. Is it correct way to send the key?
It is working when I try to submit through postman as below

Java -- HTML client returns response before the complete page load

I have to read contents of a certain field from a webpage. I have been told that I need to get the whole page and then extract the text from the html content.
I am using the following program to get the required page html content.
Now the issue is that this webpage takes a few seconds to load the actual text value that I want to read even though the rest of the static page components are loaded earlier. And my program kind of returns the html content after the static components are loaded but before my value is loaded. So, the final HTML that I get has the page loading process pic instead of the actual value.
Could anyone please guide me on the required changes in this program that would help it wait until the page is completely loaded?
HttpPost post = new HttpPost("https://..../login");
//prepare get method
HttpGet httpget = new HttpGet("https://...../value#/123");
// add parameters to the post method
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", "<name>"));
parameters.add(new BasicNameValuePair("password", "<password>"));
try {
UrlEncodedFormEntity sendEntity = new UrlEncodedFormEntity(parameters, HTTP.DEF_CONTENT_CHARSET);
post.setEntity(sendEntity);
// create the client and execute the post method
HttpClient client = HttpClientBuilder.create().build();
HttpResponse postResponse = client.execute(post);
System.out.println("Statusline: " + postResponse.getStatusLine());
//Output the Response from the POST
System.out.println(getStringFromInputStream(postResponse.getEntity().getContent()));
//releasing POST
EntityUtils.consume(postResponse.getEntity());
//Execute get
HttpContext context = new BasicHttpContext();
HttpResponse getResponse = client.execute(httpget);//, context);
System.out.println("Statusline: " + getResponse.getStatusLine());
if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(getResponse.getStatusLine().toString());
System.out.print(getStringFromInputStream(getResponse.getEntity().getContent()));
you can also use Jsoup library
visit http://jsoup.org

sending both audio file and values from android to server

i know for uploading audio in android, i can do like this :
final byte[] data = out.toByteArray();
String urlString = "http://localhost/voiceupload.php";
HttpPost postRequest = new HttpPost(urlString);
postRequest.setEntity(new ByteArrayEntity(data)); //data is a byte array containing sound in the form of bytearray
HttpClient client = new DefaultHttpClient();
for uploading simple values i can do like this :
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("callid", "8123069127952"));
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(postParameters);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost.setEntity(formEntity);
client.execute(postRequest)
Now i want to send both in one post request.I mean i want to send one or more variable values and one sound file.Can i do this ?
Sure. See my answer at this post:
Save a received picture to a folder on a web server
Just replace the image file with the sound file.
Where it passes just one value, the filename, you can add as many name-value pairs as you'd like.

Android App that logs in to HTTPS ASPX page

Just to make things clear, I have virtually no experience in HTTP. This project is very ambitious for me, but I am willing to learn in order to be able to accomplish it. I have done some searching for examples across the net, but I can't seem to find an adequate solution. I am aware of terms like GET and POST and understand the basic way to programmatically interact with a website.
Basically, the company I'm working with has a website with a database of clients that I can login to. For starters, I just want to be able to write an Android app that is able to login to the main page with my Username and Password. The site has a login URL of https://"app.companysite.com"/Security/Login.aspx?ReturnUrl=%2fHome%2fDefault.aspx and has a certificate that is for the following purpose: "Ensures the identity of a remote computer".
Is what I'm doing possible? Eventually I would like to be able to open up a Client page and edit their data and re-submit it, but one step a time.
It would be awesome if you could either point me in the direction of some relevant reading material or source code that could help me accomplish my goal.
Thanks in advance!
I don't know if this helps, but the way I did my logins is just for justification. So What I did (since I am assuming the verification is done through a MySQL database) is to create a php file that just verifies the login username and passwords are correct and print out a "correct" or "Yes" otherwise just a "No" or "invalid". Something like this :
php
//Connects to your Database
$username = $_POST['username'];
$password = $_POST['password'];
//make your mysql query if the username and password are in the database
//if there is a an approval
$approval = 1
//otherwise
$approval = 0
if ($approval > 0) {
echo "correct";
} else {
echo "invalid";
}
?>
Now in Android you could make this request to call this website and return the output like the following :
HttpParams httpParameters = new BasicHttpParams();
//make a timeout for the connections in milliseconds so 4000 = 4 seconds httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
int timeoutConnection = 4000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 4000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("your website URL");
// Add your data
String username = "your username";
String password = "your password";
List<NameValuePair> nameValuePairs;
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String lines = "";
String data = null;
ArrayList<String> al = new ArrayList<String>();
while((lines = in.readLine()) != null){
data = lines.toString();
al.add(data);
}
in.close();
//To get the response
if(al.get(0).equals("correct")){
//Your login was successful
}
else {
//Your login was unsuccessful
}
I hope this helped you a bit and pointed you in the right direction.

Categories

Resources