Sending Byte Array as POST along with BasicNameValuePairs - java

I am trying to send data to a server as POST data. I have 3 fields, one is a String, another is a TIMEDATE and the last is a BLOB.
I have been trying the following code but it doesn't seem to work. I can't turn the byte array into a String and I am unsure how to append the byte array as a parameter.
If anybody has an idea I would appreciate to hear from you !
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1/add_new_profile");
ProfileData profileData = getProfileData();
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name",profileData.getName()));
nameValuePairs.add(new BasicNameValuePair("created",profileData.getTimeCreated()));
nameValuePairs.add(new BasicNameValuePair("profile_data",new String(profileData.getDataAsByteArray())));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Server PHP script:
<?php
include('connect_db.php');
include('tools.php');
$name = $_POST['name'];
$created = $_POST['created'];
$profile_data = $_POST['profile_data'];
$query = "INSERT INTO fingerprint_profiles(name,created,fingerprint) VALUES ('".$name."','".$created"','".$fingerprint_data."')";
$result = mysql_query($query);
print_as_json($result);
?>

Related

settHeader ("content type", "") - confusion

I have a function with which I want to POST two variables to the php side, after these two variables match and the server processes the result, I want to return result in JSON. As of now my set header property looks like the following:
httppost.setHeader("Content-type", "application/json");
But while reading on at Wikipedia I found that the content type should be application/x-www-form-urlencoded and to accept JSON it should be Accept: application/json I want more clarity on this, how do I modify my code to achieve my desired result? As of now I am using local host and my POST variables seem to be not delivered on the php side. Following is my complete function:
public void parse(String last, String pwd){
String lastIndex = last;
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
System.out.println("URL is: "+CONNECT_URL);
HttpPost httppost = new HttpPost(CONNECT_URL);
httppost.setHeader("Content-type", "application/json");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", password));
nameValuePairs.add(new BasicNameValuePair("last_index", lastIndex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("Post variables(Key): "+password+"");
System.out.println("Post variables(last index): "+lastIndex);
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println("Result: "+result);
// readAndParseJSON(result);
}catch (Exception e){
System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
// return result;
}
You have a caps problem. Try "Content-Type" rather than "Content-type" (or use the const HTTP.CONTENT_TYPE).
It appears that your code is actually doing what that article describes, except that
// httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
You are adding the x-www-form-urlencoded content here
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Android: HttpPost not work

Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);

how i can retrieving result from mysql in array?

I want to get results from the database as an array. I have a table "commande" where I have stock. I want to get stock as an array. Something like this: array[0],array[],array[2]
This is the structure of my table commande (idfichecmd idproduit idclt qte datecmd)
This is my code:
String response = null;
String res = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("",));
try {
Log.i("","<<<<<<<<<<<<<<<<<<<<TRY");
response = CustomHttpClient.executeHttpPost("http://0.0.0.0/GetCmdDetails.php",nameValuePairs);
res=response.toString();
// res = res.trim();
//res= res.replaceAll("\\s+","");
//error.setText(res);
} catch (Exception e) {
Log.i("","<<<<<<<<<<<<<<<<<<<<Catch");
}
//parse json data
try{
JSONArray jArray = new JSONArray(res);
//-----------------------------------------
//nom= new String[jArray.length()];
//prenom= new String[jArray.length()];
//----------------------------------------
for (int i=0;i<jArray.length();i++) {
JSONObject json_data = jArray.getJSONObject(i)
First, test if your query is giving the correct result.
I use this solution for getting the jsonarray:
Use HttpClient to call the webservice.
private List<NameValuePair> parameters;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(//yoururl);
int statusCode = -1;
try {
httpPost.setEntity(new UrlEncodedFormEntity(this.parameters));
HttpResponse response = httpClient.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
//Get your inputstream here and convert it to json after
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

Error converting a HTTP POST response to JSON

When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.

Google Reader editing API Authentication problem

I have problem with authentication GReader editing API. I can do the HTTPS (https://www.google.com/accounts/ClientLogin) for authentication and google is returning three tokens (SID, LSID, AUTH), but no HSID.
When I try add a new feed http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll with POST data T=djj72HsnLS8293&quickadd=blog.martindoms.com/feed/ without HSID in Cookie, is response status code 401. With SID and HSID in Cookie everything works properly.
What is and where can I find this HSID string?
Thaks for your answers.
My code:
public void addNewFeed() throws IOException {
HttpPost requestPost = new HttpPost("http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll");
getSid();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DefaultHttpClient client = new DefaultHttpClient();
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
try {
nameValuePairs.add(new BasicNameValuePair("T", _token));
nameValuePairs.add(new BasicNameValuePair("quickadd", "blog.martindoms.com/feed/"));
requestPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(requestPost);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
System.out.println(str.toString());
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Looks like you might be using old info as a reference. Google switched to using auth now.
You'll need to replace getSid() with a getAuth() function.
Then this line
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
should now be this
requestPost.addHeader("Authorization", "GoogleLogin auth=" + _auth);

Categories