POST with Basic Auth fails on Android but works in C# - android

I have an app I am developing that requires me to post data to a 3rd party API. I have been struggling with authentication since the beginning and kept putting off further and further, and now I'm stuck.
I have tried using an Authenticator, but have read all about how there appears to be a bug in certain Android versions: Authentication Example
I have tried several different options, including the Apache Commons HTTP Library with no success. After all of this, I decided to make sure that the API wasn't the pain point. So I wrote a quick WinForms program to test the API, which worked perfectly on the first try. So, the idea that I'm working from and the API I working with both seem fine, but I am in desperate need of some guidance as to why the Java code isn't working.
Examples follow:
C# Code that works everytime:
System.Net.ServicePointManager.Expect100Continue = false;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(addWorkoutUrl);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "distance=4000&hours=0&minutes=20&seconds=0&tenths=0&month=08&day=01&year=2011&typeOfWorkout=standard&weightClass=H&age=28";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.Headers["X-API-KEY"] = apiKey;
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Java code for Android that currently returns a 500:Internal Server Error, though I believe this is my fault.
URL url;
String data = "distance=4000&hours=0&minutes=20&seconds=0&tenths=0&month=08&day=01&year=2011&typeOfWorkout=standard&weightClass=H&age=28";
HttpURLConnection connection = null;
//Create connection
url = new URL(urlBasePath);
connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(10000);
connection.setUseCaches(false);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("X-API-KEY", apiKey);
connection.setRequestProperty("Authorization", "Basic " +
Base64.encode((username + ":" + password).getBytes("UTF-8"), Base64.DEFAULT));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes("UTF-8").length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(data.getBytes("UTF-8"));
wr.flush();
wr.close();
statusCode = connection.getResponseCode();
statusReason = connection.getResponseMessage();
//At this point, I have the 500 error...

I figured out the problem, and the solution finally after stumbling across the root cause as mentioned in the comment above.
I was using Base64.encode() in my example, but I needed to be using Base64.encodeToString().
The difference being that encode() returns a byte[] and encodeToString() returns the string I was expecting.
Hopefully this will help somebody else who is caught by this.

Here's a nicer method to do to the POST.
install-package HttpClient
Then:
public void DoPost()
{
var httpClient = new HttpClient();
var creds = string.Format("{0}:{1}", _username, _password);
var basicAuth = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(creds)));
httpClient.DefaultRequestHeaders.Add("Authorization", basicAuth);
var post = httpClient.PostAsync(_url,
new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "name", "Henrik" },
{ "age", "99" }
}));
post.Wait();
}

I have tried this in java
import java.io.*;
import java.net.*;
class download{
public static void main(String args[]){
try{
String details = "API-Key=e6d871be90a689&orderInfo={\"booking\":{\"restaurantinfo\":{\"id\":\"5722\"},\"referrer\":{\"id\": \"9448476530\" }, \"bookingdetails\":{\"instructions\":\"Make the stuff spicy\",\"bookingtime\": \"2011-11-09 12:12 pm\", \"num_guests\": \"5\"}, \"customerinfo\":{\"name\":\"Ramjee Ganti\", \"mobile\":\"9345245530\", \"email\": \"sajid#pappilon.in\", \"landline\":{ \"number\":\"0908998393\",\"ext\":\"456\"}}}}";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "1234".toCharArray());
}
});
HttpURLConnection conn = null;
//URL url = new URL("http://api-justeat.in/ma/orders/index");
URL url = new URL("http://api.geanly.in/ma/order_ma/index");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput (true);
conn.setRequestMethod("POST");
//conn.setRequestMethod(HttpConnection.POST);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.writeBytes(details);
outStream.flush();
outStream.close();
//Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();
System.out.println(conn.getResponseCode() + "\n\n");
}catch(Exception e){
System.out.println(e);
}
}
}
this could help.

Related

Android send POST request in Java to ASP.net Web API

When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.
String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));
OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();
When executing the above code, it will have an FileNotFoundException in
conn.getInputStream()
I also tried to implement source code in HttpClient style.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);
try {
StringEntity se = new StringEntity((new Gson()).toJson(data));
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
String result = "";
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.i("RESPONSE", result);
} catch (Exception ex) {
Log.i("Exception", ex.getMessage());
}
return output;
And this time, it shows "The requested resource does not support http method 'get'".
I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?
Finally, the following coding is my ASP.net Web API for reference.
[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.
When the request Content-Type is "application/json",
Using string, The request body should be a plain text (e.g. "Text Message").
[FromBody] string inStr
Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })
[FromBody] YourClass inObj
Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])
[FromBody] YourClass[] inObj
And the self-defined class should be like as following:-
class YourClass {
public string KEY { get; set; }
}
Btw. Thanks for all reply and useful information.

Android HttpURLConnect POST Stream Size

I am trying to follow the tutorial here https://developer.android.com/reference/java/net/HttpURLConnection.html
to make a post call in android. The issue I am having it I am not sure how to write the post call to the http connection.
URL url = new URL("https://chart.googleapis.com/chart");
HttpURLConnection client = null;
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setRequestProperty("cht", "lc");
client.setRequestProperty("chtt", "This is | my chart");
client.setRequestProperty("chs", "300x200");
client.setRequestProperty("chxt", "x");
client.setRequestProperty("chd", "t:40,20,50,20,100");
client.setDoOutput(true);
client.setChunkedStreamingMode(0);
OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
outputPost.write(client.getRequestProperties().toString().getBytes());
outputPost.flush();
outputPost.close();
InputStream in = new BufferedInputStream(client.getInputStream());
Log.d(TAG, "Input" + in.read());
client.disconnect();
} catch (MalformedURLException error) {
//Handles an incorrectly entered URL
Log.d(TAG, "MalformedURL");
} catch (SocketTimeoutException error) {
//Handles URL access timeout.
Log.d(TAG, "Socket Timeout");
} catch (IOException error) {
//Handles input and output errors
Log.d(TAG, "IOexception");
}
The tutorial uses a custom method to write the stream but I still run into writing an unknown number of bytes for the body of the POST.
Questions to consider:
Does the Google chart API require information to be sent via the header variables?
Does the Google chart API require information to be sent in the body?
Is the information in the body being sent in the correct format?
Missing Content-Type header variable
Why is the same data being set in the header and body?
After reading the Google Chart Guide the following code will successfully make a POST request to the Google Chart API and retrieve the image as bytes.
To write the post data see the following line in the getImage code sample: con.getOutputStream().write(postDataBytes);
Take note of the following line to set the post size: con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
public byte[] getImage() throws IOException {
URL obj = new URL("https://chart.googleapis.com/chart");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Store the post data
Map<String,Object> params = new LinkedHashMap<>();
params.put("cht", "lc");
params.put("chtt", "This is | my chart");
params.put("chs", "300x200");
params.put("chxt", "x");
params.put("chd", "t:40,20,50,20,100");
// Build the post data into appropriate format
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
con.setDoOutput(true);
// post the data
con.getOutputStream().write(postDataBytes);
// opens input stream from the HTTP connection
InputStream inputStream = con.getInputStream();
// read the data from response
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = inputStream.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
inputStream.close();
return baos.toByteArray();
}

Not able to POST to REST API

Today I'm making my first attempt of sending a POST request with a JSON to save some data, and I'm not being able to do so.
My app works by signing in, and then save, modify and delete data. It's already done in iOS, but since I'm new to Android, I'm not sure how to do it.
Here's my POST function:
public String POST(String targetURL, String urlParameters, String user, String pwd) {
URL url;
String u = targetURL;
HttpURLConnection connection = null;
try {
// Create connection
// u=URLEncoder.encode(u, "UTF-8");
url = new URL(u);
connection = (HttpURLConnection) url.openConnection();
// cambiarlo luego al usuario q esta logeado
String login = user + ":" + pwd;
String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(login)));
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Content-Type", "plain/text");// hace q sirva con el string de json
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(120000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
this.setResponseCode(connection.getResponseCode());
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
The method above is executed with Asynctask, and even if I use it to Login using Spring security, it works, and even I can save for internal usage the username, password, and secret token.
I dunno if I need to put the token in a header or something, because I already did that, with no positive results.
I'm supposing that the only permission I need to execute this is the internet one, so in my manifest file I specified that permission.
I'm going crazy with this issue, please help!
Thanks in advance.
EDIT:
Sorry guys, I'm kinda new to this way of asking, and also, not an English native speaker :P
The output I receive after sending the request, is the HTML of the page that handles logging in into the web app... I need like a json response or something like that to make sure the request was saved correctly
Try handling your cookies
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This should be a singleton.

Error on using googmaps api

Im getting the following error on trying to use an web service from google api maps:
{
"error_message" : "Requests to this API must be over SSL.",
"results" : [],
"status" : "REQUEST_DENIED"
}
the url used to invoke the web service:
http://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
method used to call the web service:
enter code here
public static String httpPost(String urlStr) throws Exception {
String novaUrl = urlStr.trim();
novaUrl = urlStr.replaceAll(" ", "+");
novaUrl = novaUrl.replaceAll("\r", "");
novaUrl = novaUrl.replaceAll("\t", "");
novaUrl = novaUrl.replaceAll("\n", "");
URL url = new URL(novaUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urldecoded");
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.close();
out.close();
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
Spanned retorno = Html.fromHtml(sb.toString());
return retorno.toString();
}
How to solve this problem?
Thanks.
Try using this URL. Error just because of http and https. https is used for secure line.
https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
Now when you click on this you will get some error like this .. The provided API key is invalid.
For that just provide correct API key that you retrieved from Google Console.
Your given URL :: https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
here key=my_key Here is the problem, please provide correct API key and you problem will be solved.

Sending special characters (ë ä ï) in POST body with DataOutputStream in Android

Im currently working on an Android app with heavy server side communication. Yesterday I got a bug report saying that the users aren't able to send (simple) special characters such as ëäï.
I searched but didn't find anything helpful
Possible duplicate ( without answer ):
https://stackoverflow.com/questions/12388974/android-httpurlconnection-post-special-charactes-to-rest-clint-in-android
My relevant code:
public void execute(String method) {
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(this.url);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setReadTimeout(30 * 1000);
urlConnection.setDoInput(true);
if (secure)
urlConnection.setRequestProperty("Authorization", "Basic " + getCredentials());
if (body != null) {
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setFixedLengthStreamingMode(body.length());
urlConnection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(body);
dos.flush();
dos.close();
}
responseCode = urlConnection.getResponseCode();
message = urlConnection.getResponseMessage();
InputStream in = null;
try {
in = new BufferedInputStream(urlConnection.getInputStream(), 2048);
} catch (Exception e) {
in = new BufferedInputStream(urlConnection.getErrorStream(), 2048);
}
if (in != null)
response = convertStreamToString(in);
} catch (UnknownHostException no_con) {
responseCode = 101;
}catch (ConnectException no_con_2){
responseCode = 101;
}catch(IOException io_ex){
if(io_ex.getMessage().contains("No authentication challenges found")){
responseCode = 401;
}else
responseCode = 101;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
body is a String ;-)
Hope we can solve this together
UPDATE:
Tried:
writeUTF()
need a server capable of understanding the modified UTF-8
byte[] buf = body.getBytes("UTF-8");
dos.write(buf, 0, buf.length);
strings work but no special chars
update: Got it working with StringEntity(* string, "UTF-8") then parse the result to a byte[] and write it with dos.write(byte[])!
--
Setting the encoding of the StringEntity did the trick for me:
StringEntity entity = new StringEntity(body, "UTF-8");
seen here: https://stackoverflow.com/a/5819465/570168
i am not totally sure buy try this utility for your case
URLEncoder.encode(string, "UTF-8")
I faced this problem in android while passing a json with special char (ñ).
In my WebApi method, [FromBody] param is giving null, it seems it can't parse the json.
I got it working by getting bytes as UTF-8 then writing it in DataOutputStream (Client-side fix).
byte[] b = jsonString.getBytes("UTF-8");
os.write(b, 0, b.length);

Categories

Resources