Post form data to server Api (Android) - java

I need to submit my registration form details to server api. I have tried one method by calling a function on button click.But nothing is geting posted in the server and I am also not getting any exception.Please help me.
Thanks in advance.
Below is the code .
I have called the function like this
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
ex.printStackTrace();;
Toast.makeText(getActivity(),"URL Exception", Toast.LENGTH_LONG).show();
}
And below given is the function
public String GetText() throws UnsupportedEncodingException
{
HttpURLConnection connection = null;
// Get user defined values
Name = full_name.getText().toString();
Phonenumber = phone.getText().toString();
Email=email.getText().toString();
Password=password.getText().toString();
House = house.getText().toString();
Street = street.getText().toString();
Landmark = landmark.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(Password, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8")
+ "=" + URLEncoder.encode(Phonenumber, "UTF-8");
data += "&" + URLEncoder.encode("house", "UTF-8")
+ "=" + URLEncoder.encode(House, "UTF-8");
data += "&" + URLEncoder.encode("street", "UTF-8")
+ "=" + URLEncoder.encode(Street, "UTF-8");
data += "&" + URLEncoder.encode("areaname", "UTF-8")
+ "=" + URLEncoder.encode(Area, "UTF-8");
data += "&" + URLEncoder.encode("landmark", "UTF-8")
+ "=" + URLEncoder.encode(Landmark, "UTF-8");
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://application.easypani.com/app/customer/register");
// Send POST data request
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(data.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes(data);
wr.flush();
wr.close();
// Get the server response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
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();
}
}
}

Use this instead
private class PostData extends AsyncTask < String, Void, Void > {
protected Void doInBackground(String...params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://application.easypani.com/app/customer/register");
try {
// Add your data
String Name = params[0];
String Phonenumber = params[1];
String Email = params[2];
String Password = params[3];
String House = params[4];
String Street = params[5];
String Landmark = params[6];
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
nameValuePairs.add(new BasicNameValuePair("name", Name));
nameValuePairs.add(new BasicNameValuePair("email", Email));............................................................
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
}
And you use it like this
new PostData().execute(Name, PhoneNumber..and so on);

Related

Microsoft graph search feature Java

I'm trying to use Microsoft Graph to make a file search. I use this entry point : https://graph.microsoft.com/beta/search/query
My application do not use a user account but a daemon with an application key (see auth method).
And i send a built object.
My java code is rather simple :
public static void main(String[] args) throws Exception{
try {
// Authentication result containing token
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
String token = result.accessToken();
SearchDocumentResponseModel documentQuery = fileGraphs.searchDocument(token, QUERYSTRING, 0, 25);
System.out.println("Find a document" + documentQuery.toString());
} catch(Exception ex){
throw ex;
}
}
private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
CONFIDENTIAL_CLIENT_ID,
ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
.authority(TENANT_SPECIFIC_AUTHORITY)
.build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(GRAPH_DEFAULT_SCOPE))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
The SearchDocumentResponseModel is just a set of POJO that build for me the object that i must send as a request body.
{
"requests":
[{
"entityTypes":["microsoft.graph.driveItem"],
"query":{"query_string":{"query":"any query"}},
"from":0,"size":25
}]
}
The method searchDocument is just here to build the object before i send it to the API
public SearchDocumentResponseModel searchDocument(String accessToken, String stringSearch, int from, int size) throws IOException {
SearchDocumentRequestModel searchRequest = new SearchDocumentRequestModel();
// set values here
...
URL url = new URL("https://graph.microsoft.com/beta/search/query");
return requestsBuilder.buildPostRequest(accessToken, searchRequest, url)
}
Now i want to send to server the Json and expect an answer :
public SearchDocumentResponseModel buildPostRequest(String accessToken, SearchDocumentRequestModel searchRequest, URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// write the input json in a string
String jsonInputString = new Gson().toJson(searchRequest);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
String httpResponseMessage = conn.getResponseMessage();
// reading the response
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String outputResponse = response.toString();
return new Gson().fromJson(outputResponse, SearchDocumentResponseModel.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I think i set the properties correctly. Is it coming from my code or from Microsoft Graph ? Thanks !
First of all, you should check if the access token is valid, you can send a request using postman.
If the token is valid, I think it should be the problem of your jsonInputString. The following code works fine.
URL url = new URL("https://graph.microsoft.com/beta/search/query");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "access_token" );
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String str = "";
str += "{";
str += " \"requests\": [";
str += " {";
str += " \"entityTypes\": [";
str += " \"microsoft.graph.driveItem\"";
str += " ],";
str += " \"query\": {";
str += " \"query_string\": {";
str += " \"query\": \"contoso\"";
str += " }";
str += " },";
str += " \"from\": 0,";
str += " \"size\": 25";
str += " }";
str += " ]";
str += "}";
OutputStream os = conn.getOutputStream();
byte[] input = str.getBytes("UTF-8");
os.write(input, 0, input.length);
System.out.println(conn.getResponseCode());
Update:
Query api doesn't support client credential flow.

ANDROID - How to get return success from web service in android using httpurlconnection?

I've a return 0 from web services using postman if the data send successfully.
but I'm quite confused how to detect 0 message in android using HttpURLConnection
in HttpClient I'm using String response = httpclient.execute(httppost, responseHandler);
String response = httpclient.execute(httppost, responseHandler);
Log.d("MainActivity", "INSERT:" + response);
but refer to the docs
there's some code like getResponseCode() getResponseMessage() but the output is 200 for getResponseCode() and OK for getResponseMessage()
so how to get output of 0 in HttpURLConnection?
EDIT urlconnection code:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
int respon = conn.getResponseCode();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("Input", String.valueOf(conn.getInputStream()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
This is how you need to read the data from the server using HttpUrlConnection:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
InputStream is = null;
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = conn.getInputStream();// is is inputstream
} else {
is = conn.getErrorStream();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String response = sb.toString();
//HERE YOU HAVE THE VALUE FROM THE SERVER
Log.d("Your Data", response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}

Login twitter with username and password, POST java

I get OAuthToken, Authenticity Token from the libarary Twitter4j (it is correctly, becouse when I login in browser its works). Then try to login twiiter with password and username with POST request:
URL url = new URL("https://api.twitter.com/oauth/authorize");
Add parametrs to request:
String params = "oauth_token" + "=" + oAuthToken;
params += "&" + "session[username_or_email]" + "=" + login;
params += "&" + "session[password]" + "=" + password;
params += "&" + "redirect_after_login" + "=" + "https://twitter.com/oauth/authorize?oauth_token=" + oAuthToken;
params += "&" + "authenticity_token" + "=" + authToken;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
output.write(params);
output.flush();
get response:
StringBuilder sb = new StringBuilder();
int httpResult = connection.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
br.close();
PrintWriter out = new PrintWriter("response.html");
out.print(sb);
out.close();
out.flush();
System.out.println(getVerifier(sb.toString()));
} else {
System.out.println("Response: " + connection.getResponseMessage() + ", Status: " + httpResult);
}
But nothing happens, in response I have HTML page, where I can login twitter.

Mysql insert statement and passing parameters to PHP

I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).
In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP script:
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
String urlString = "phpfilelocation.php" + "?" + data;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.connect();
//remove:
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP :
mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");
JAVA :
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");

Uploading Image To Imgur

I want to upload an image from my harddrive to imgur and return the direct link to it so that
the image can be added to forum posts inside image tags or whatever.
I already registered on imgur and got a client id for my application. I tried various code examples on stackoverflow but none worked. Please help me to get working code for this. See below for the ones I tried.
// Stuck after "Connecting..."
public static void upload(BufferedImage image)
{
String IMGUR_POST_URI = "https://api.imgur.com/3/upload";
String IMGUR_API_KEY = CLIENT_ID;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.out.println("Writing image...");
ImageIO.write(image, "png", baos);
URL url = new URL(IMGUR_POST_URI);
System.out.println("Encoding...");
String data = URLEncoder.encode("image", "UTF-8")
+ "="
+ URLEncoder.encode(
Base64.encodeBase64String(baos.toByteArray())
.toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "="
+ URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
System.out.println("Connecting...");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", "Client-ID "
+ IMGUR_API_KEY);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
System.out.println("Sending data...");
wr.write(data);
wr.flush();
System.out.println("Finished.");
// just display the raw response
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
} catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
Another example:
// Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
public static String getImgurContent(String imageDir, String clientID)
throws Exception
{
URL url;
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(imageDir, "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
stb.append(line).append("\n");
}
wr.close();
rd.close();
return stb.toString();
}
And finally:
// null : null
public static String Imgur(String imageDir, String clientID)
{
// create needed strings
String address = "https://api.imgur.com/3/image";
// Create HTTPClient and post
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
// create base64 image
BufferedImage image = null;
File file = new File(imageDir);
try
{
// read image
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = new Base64().encodeAsString(byteImage);
// add header
post.addHeader("Authorization", "Client-ID " + clientID);
// add image
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("image", dataImage));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute
HttpResponse response = client.execute(post);
// read response
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String all = null;
// loop through response
while (rd.readLine() != null)
{
all = all + " : " + rd.readLine();
}
return all;
} catch (Exception e)
{
return "error: " + e.toString();
}
}

Categories