upload file to server in android - android

i want to upload a file from my android phone to server URL. but the server required login first. how can i do this to upload the file to this server URL with also login URL.
for example:
uploading url:
http://api.someapi.net/v1/medium/14
parameters required: file and title
login url:
http://api.someapi.net/v1/user/login
parameters required: email and password

Check the login credentials by using the code below. If the response is OK send the file to the url using the same code below with different parameters. Else do whatever you want.
URL siteUrl;
try {
siteUrl = new URL("yoururl");
HttpURLConnection conn = (HttpURLConnection) siteUrl
.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content1 = "";
//Here param is the Map<String,String> which holds the value of email and password
Set getkey = param.keySet();
Iterator keyIter = getkey.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
content += key + "=" + param.get(key);
}
//Check by printing here
System.out.println(content);
out.writeBytes(content.trim());
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
}
Hope it helps

You need Apache's Mime4J jar file on your project (here - http://james.apache.org/download.cgi#Apache_Mime4J )
And do:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new InputStreamBody(file, "UPLOAD.jpg"));
request.setEntity(entity);
Tada!

Related

Why am I getting 500 response code on passing wrong email or password to service in android?

I have been running into a very strange problem. I am trying to implement log in service in my app. When I pass right email and password service returns response as expected(means no error comes) but when I delibrately pass wrong email or password geInputStream() method throws FileNotFoundException. I don't know what is the reason behind this.Further more, before calling getInputStream() method i checked status code as well(this is the case when I am passing wrong email and password intentionally).The status code was 500. I checked for 500 and that was internal server error. My question is why is that so? I mean when intentionally passing wrong email or password why internal server occurred? One more thing I would like to mention that I have checked the same service on post man it is working fine as expected. If i pass wrong email or password postman returns the expected error. Below is the code I am using
private String invokeWebservice() {
String data = null;
HttpURLConnection conn = null;
BufferedReader in = null;
try {
String webservice = Constants.BASE_URL + serviceName;
LogUtility.debugLog("webservice just called "+ webservice);
URL url = new URL(webservice);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setUseCaches(false);
if (isPost) {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
if (jsonObject != null)
writer.write(jsonObject.toString());
writer.close();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null)
sb.append(l + nl);
in.close();
data = sb.toString();
return data;
} catch (Exception e) {
LogUtility.errorLog("exception while calling web service");
} finally {
try {
if (conn != null)
conn.disconnect();
if (in != null)
in.close();
} catch (Exception ex) {
// LogUtility.errorLogWithException(ex, ex.getMessage());
}
}
return data;
}
Any help?
After spending some time now I was able to solve my problem.Posting my answer for others. Passing wrong email and password to the service was right and server was consuming those parameters as well and because there was an error(because email and password) that is why it was returning 500 code. So, I checked for status code if it was 200 then I used getInputStream() method and else i called getErrorStream() method. By this way i got the stream that has property for error(this property contains error detail). Below is the code i used
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
Hope it helps other as well.

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.

how I get the html source with utf-8 format?

I write this code to get html source from a site.
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "aranan="+et.getText();
try
{
url = new URL("http://www.fragmanfan.com/arama.asp");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
browser.loadDataWithBaseURL(null, response,"text/html", "UTF-8", null);
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}
});
But there is a one problem.It is : response (the variable that have html source) is not utf-8 format.
How I can fix this?
Thanks.
.
.
.
InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"ISO-8859-9");
.
.
.
Since your response seems to be your HTML webpage in a single String, you should make sure that the head tag of your page cointains the label that defines the codification.. if not you can append it yourself to your StringBuilder.
Here is how you can do it:
final StringBuilder sb =
new StringBuilder("<html><head>"+ "<meta http-equiv=\"content-type\"content=\"text/html;charset=utf-8\" />"+ "</head><body>");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
sb.append(response);
sb.append("</body></html>");
and then you can properly load your HTML to your webview / browser. (this worked for me so I know for sure that it actually works =] )
p.d. make sure to accept the answer that properly answer your question so people keep answering your future questions.
https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work

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

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.

How do I send a request to different page on the logged site

First, I want to connect to the site.
After, I want to get a data from different page with this connection
sample:
1- connect to http://site.com/Login with user pass
2- get a secret data from http://site.com/Secret
How do I do this, pleas help me...
OutputStreamWriter request = null;
url = new URL("http://site.com/Login");
String response = null;
EditText user = (EditText)this.findViewById(R.id.user);
EditText pass = (EditText)this.findViewById(R.id.pass);
String parameters ;
try {
System.setProperty("http.keepAlive", "true");
url = new URL("http://site.com/Home/Login");
httppost = (HttpURLConnection) url.openConnection();
httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("User-Agent", "Mozilla/5.0 Linux U Android 2.3.3 tr-tr HTC_DesireHD_A9191 Build/GRI40 AppleWebKit/533.1 KHTML, like Gecko Version/4.0 Mobile Safari/533.1");
httppost.setRequestProperty("Accept_Language", "en-US");
httppost.setRequestProperty("Connection", "Keep-Alive");
httppost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(httppost.getOutputStream());
parameters = "username="+user.getText()+"&password="+pass.getText();
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(httppost.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
Toast.makeText(this,response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
You should use WebView and sorry but you can not get the webview content.
If you own the server-side code and you want to access from java then you should use an access token for more secure connection and get data by using JSON or XML. Or there is a much more secure connection type which is OAuth2.
If you don't own server, you should show the http://site.com/Login url in webview. When the user logins than you have cookie in your webview. You can use CookieManager http://developer.android.com/reference/android/webkit/CookieManager.html and send the data by using this cookie and get the result. This method is not easy and can differentiate according to server-side implementation.

Categories

Resources