This is for an Android application ,where my mobile developer is trying to post json data to my PHP page .
Below is the function that is being used :
public static String postData(String url, String postData) {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new StringEntity(postData));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
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());
//throw new CustomException("Could not establish network connection");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
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());
//throw new CustomException("Error parsing the response");
}
return result;
}
Where url is the link to my php webpage . On my php page , i am just trying to print out the posted data by doing :
print_r($_POST);
But it shows an empty array . I even tried using the REST addon for firefox and doing the same but it simply shows a blank array .
Would be great if someone could point out if i am missing anything .
Thanks.
you need to get the json content like below :
if(isset($_POST))
{
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
echo $jsonObj;
}
Related
While trying to run a httppost at my client (Android application) side using the below code, but on my browser, i do receive just the JSON output of the expected data.
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.43.229/thecee/mobile_app/the_lost.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("The Content", result);
} catch (Exception e) {
// Oops
}
finally{
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
I am getting the error message below while trying to parse it.
03-31 04:29:50.463 18871-19413/com.example.ji.thecce D/The Content:
http://www.w3.org/1999/xhtml'>
The request failed
Response Error.
Technical description:502 Bad Gateway - Response Error, a
bad response was received from another proxy server or the destination
origin server.
03-31 04:29:50.466 18871-18871/com.example.ji.thecce
W/System.err: org.json.JSONException: Value
I will sincerely appreciate your response.
Thanks for your time.
i have written an android app which post data to my database. The app should access an webservice which post the data to the database. the webservice works fine. ive testet it with my browser, he is already on the server. now i want my app to execute the webservice. but that doesnt work. My debugger doesnt work too so im not able to debug. here is my code to for accessing the webservice. any ideas??
public class PostBlog extends AsyncTask<String, Void, String> {
String BlogURL;
public PostBlog(String insertBlogURL) {
BlogURL = insertBlogURL;
}
#Override
protected String doInBackground(String... params) {
postBlogData(BlogURL);
return null;
}
public void postBlogData(String url) {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 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) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
The Class is called from my main Activity by
new PostBlog(insertBlogURL).execute("");
Is there another easier way to execute my ".jsp?asdd=sdsd" file on the server?
Thanks for your ideas.
Instead of doing :
new PostBlog(insertBlogURL).execute("");
Change your constructor and retrieve the url from the doInBackground method, by doing params[0]
Then initiate the download like this
PostBlog blogPoster = new PostBlog();
try {
blogPoster.execute(insertBlogURL);
} catch (InterruptedException e) {} catch (ExecutionException e) {}
I should say this is a modified snippet of code from my own project, so it might not work exactly the way you expect.
public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.
This question already has answers here:
Android, Java: HTTP POST Request
(8 answers)
Closed 7 years ago.
I am doing a post request in Android. It should give me a response in the form of a string. Thats what i do to check it. However it gives me an empty string back. It's in the toast message. Am i doing something wrong, any hints for me guys?
private void makePostRequest() throws UnsupportedEncodingException {
SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
String password = postpreference.getString("Password", null);
String username = postpreference.getString("Username", null);
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader = null;
try {
// send post data request
URL url = new URL("secreturl but working");
URLConnection conn = url.openConnection();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(data);
streamWriter.flush();
//read the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
// Show response on activity
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
Check for response code. Then only get the response if you are getting the correct response code.
int responseCode = conn.getResponseCode();
I fixed it following the first solution in this link : Android, Java: HTTP POST Request
Thanks for help
Edit : Correct way to do the post request.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
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
}
Here my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("dropbox link to php code");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
System.out.println(is);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("1 " + result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch (JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
The link in the HTTPPost is a download link to the PHP code on Dropbox. That code looks like this:
<?php
mysql_connect("host","username","password");
mysql_select_db("1487057_test");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
The problem is that the PHP code does not seem to be "executed" by the HTTPClient. When I do a print of the input stream, I just get back the first two lines of the PHP code. The JSON log does not seem to print at all. Anyone see what's wrong?
If you have the json data from ftp server it will work fine, since u r
using dropbox for php file, u need to make sure that it works, would
suggest you to test service on browser first if it works fine then u
can move ahead with code.possibly setup the ftp instead of Dropbox as
file server.
modify your PHP to something like:
<?php
$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
mysql_query("set names utf8");
$result = mysql_query($sql);
while ($e = mysql_fetch_assoc($result)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close($dbhost);
?>