Android post JSON - android

hy,
I'd like to insert a person into the database, so I have to post the name and firstname
here is json url http://localhost:8075/myproject/personne/new
I thought to use
Map map = new HashMap ();
map.put ("name", "aaaaa");
map.put ("firstname", "eee");
but , I do not know WHAT TO DO to post the variables in the server.

you have to create a server side page, for example insert.php.
Then make httppost from your android application to server side page("insert.php")
here is an example about connect to remote database in android

I'm assuming you already have your server up and running (so it's already accepting and handling post requests). Please also use an IDE that manages the imports automatically, I just added them for reference.
Following code is copy/paste from one of my projects and untested (please also excuse invalid references I might have missed).
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
private Response execute(String jsonData) {
String url = "http://localhost:8075/myproject/personne/new";
HttpPost post = new HttpPost(url);
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("data", jsonData));
try {
post.setEntity(new UrlEncodedFormEntity(parameters));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
return parseResponse(response);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported encoding in JSON data", e);
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol based error", e);
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
}
return null;
}
private Response pushPerson(Person person) {
try {
JSONObject json = new JSONObject();
json.put("firstname", person.firstname);
json.put("lastname", person.lastname);;
return execute(json.toString());
} catch (JSONException e) {
Log.e(TAG, "Error pushing person", e);
}
return null;
}
As you can see there's no need for a HashMap, the JSONObject is what you are looking for. The Response can be nearly anything, that's up to you. "Normally" you would return the id of the newly created person.
There are plenty of tutorials out there. When I started I found each of them just by using a search engine. Please also always take a look at the Android docs.

Related

How to upload a video from an Android device, to a server or a host and then retrieve it again?

Now am building an android application where i want the user to upload video to the server, then after uploading it, it should appear on the MainActivity, I've set up the login/register using Firebase but Firebase doesn't support streaming Videos(according to my attempts), thus i've been googling for long time about servers and how servers work with video uploading and streaming but i've reached an end point.
What i want to do is, building a system where user can upload a video from his local device, into a server, and then downloading(video streaming from a server), so the user later on can interact with it. I am not sure how to do it, i have searched a lot but couldn't find what i needed to do/learn
How you upload the video and how you make it available are really two separate questions.
For uploading from Android:
There are a number of libraries you can use to upload to Android - the code below uses the apache multipart client and it is tested and works. Other http libraries include Volley and retrofit.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
public class VideoUploadTask extends AsyncTask<String, String, Integer> {
/* This Class is an AsynchTask to upload a video to a server on a background thread
*
*/
private VideoUploadTaskListener thisTaskListener;
private String serverURL;
private String videoPath;
public VideoUploadTask(VideoUploadTaskListener ourListener) {
//Constructor
Log.d("VideoUploadTask","constructor");
//Set the listener
thisTaskListener = ourListener;
}
#Override
protected Integer doInBackground(String... params) {
//Upload the video in the background
Log.d("VideoUploadTask","doInBackground");
//Get the Server URL and the local video path from the parameters
if (params.length == 2) {
serverURL = params[0];
videoPath = params[1];
} else {
//One or all of the params are not present - log an error and return
Log.d("VideoUploadTask doInBackground","One or all of the params are not present");
return -1;
}
//Create a new Multipart HTTP request to upload the video
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serverURL);
//Create a Multipart entity and add the parts to it
try {
Log.d("VideoUploadTask doInBackground","Building the request for file: " + videoPath);
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename:" + videoPath);
StringBody description = new StringBody("Test Video");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);
} catch (UnsupportedEncodingException e1) {
//Log the error
Log.d("VideoUploadTask doInBackground","UnsupportedEncodingException error when setting StringBody for title or description");
e1.printStackTrace();
return -1;
}
//Send the request to the server
HttpResponse serverResponse = null;
try {
Log.d("VideoUploadTask doInBackground","Sending the Request");
serverResponse = httpclient.execute( httppost );
} catch (ClientProtocolException e) {
//Log the error
Log.d("VideoUploadTask doInBackground","ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
//Log the error
Log.d("VideoUploadTask doInBackground","IOException");
e.printStackTrace();
}
//Check the response code
Log.d("VideoUploadTask doInBackground","Checking the response code");
if (serverResponse != null) {
Log.d("VideoUploadTask doInBackground","ServerRespone" + serverResponse.getStatusLine());
HttpEntity responseEntity = serverResponse.getEntity( );
if (responseEntity != null) {
//log the response code and consume the content
Log.d("VideoUploadTask doInBackground","responseEntity is not null");
try {
responseEntity.consumeContent( );
} catch (IOException e) {
//Log the (further...) error...
Log.d("VideoUploadTask doInBackground","IOexception consuming content");
e.printStackTrace();
}
}
} else {
//Log that response code was null
Log.d("VideoUploadTask doInBackground","serverResponse = null");
return -1;
}
//Shut down the connection manager
httpclient.getConnectionManager( ).shutdown( );
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//Check the return code and update the listener
Log.d("VideoUploadTask onPostExecute","updating listener after execution");
thisTaskListener.onUploadFinished(result);
}
To make the video available on the server side you just need a HTTP server that can server static content or a video streaming server - the latter will allow you use Adaptive Bit Rate Streaming (ABR - e.g. HLS or DASH) for better quality, but may be overkill for your needs.
Either approach will provide you withe a URL for the video which you can use an Android player like ExoPlayer to play back the video with:
https://github.com/google/ExoPlayer

how to write the AsyncTask in JSON parser for my code?

I am developing a login application using MySQL database. I am using JSONParser from the database package to connect to the local mysql database I am getting the following error please some one help me. I googled for this error but what I got is to use the AsyncTask but I don't know where to use and how to use and what is the Mainthread also.
Please some one edit my code and explain or post relevant codes...
"android.os.NetworkonMainThreadException" is the error when I running the application from 4.2 genymotion emulator...
package com.android.database;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}``
Network Operations must be done in background.
You can use AsyncTask to accomplish this.
You are performing network operation on the UI thread and you can't do it. Consider using AsyncTask to do this kind operations, or an external library like this, which allows you to make Http request asynchronously in a very simple way.
I'm not sure if I understand your question correctly, and I would like to rather add a comment but am not allowed (too low rep) so here goes:
This class JSONParser i'm assuming is the "Activity" you are talking about. This is not an activity though, but a class, so you could rather create a new object of this class and use it from your calling activity:
JSONParser json = new JSONParser();
json.getJSONFromUrl(url,params);
Thing is, doing this parsing will take time and on the main UI thread this will probably pause the thread and might even let the app crash if the thread takes longer than 5 seconds to respond. This means you should use AsyncTask to run this JSONParser methods. A good place to start with learning AsyncTask is Vogella. He has some great tutorials on his site.
You will probably use doInBackground to run your getJSONFromUrl method and then update your UI thread from the onPostExecute method. So basically: Use AsyncTask

Unable to find com.google.api.client.htpp.javanet.NetHttpTransport in Android Application

I am trying to implement http://codify.freebaseapps.com/?request=https%3A%2F%2Fwww.googleapis.com%2Ffreebase%2Fv1%2Fsearch%3Fquery%3DBlue%2BBottle&title=Simple%20Search inside an android application. I have the correct api key installed and matched to the google api service and have imported the appropriate jar files under Referenced Libraries.
My code however keeps throwing a could not find class - 'com.google.api.client.http.javanet.NetHttpTransport' error every time it is run on the emulator. Any suggestions or feedback ?
You must add library into project.
right click project
Properties
Java Build Path
Add External JARs
please read this post: Android and Google client API NetHttptransport Class not found
When I built the Codify app that you linked to I didn't test it against Android so there may be an easier way to do it in Android.
Here's another way to do it using Apache HttpClient and json.org which are included in the Android SDK.
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FreebaseSearchTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject getJsonContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException, JSONException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
JSONObject jObject = new JSONObject(out.toString());
return jObject;
}
#Override
protected JSONObject doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String query = params[0];
JSONObject result = null;
try {
HttpGet httpGet = new HttpGet("https://www.googleapis.com/freebase/v1/search?query=" + URLEncoder.encode(query, "utf-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
result = getJsonContentFromEntity(entity);
} catch (Exception e) {
Log.e("error", e.getLocalizedMessage());
}
return result;
}
protected void onPostExecute(JSONObject result) {
doSomething(result);
}
}

Error with using HttpPost on Android

I am trying to input text from Android into websites, and I read that httppost is a good option. I download the HttpClient 4.2.2 (GA) tar.gz, unzipped them, and copied the 7 jars into the lib folder of my android project in Eclipse. I'm pretty sure I got all the jars, since they matched those listed on the website.
I then proceeded to copy and paste the top tutorial from: http://hc.apache.org/httpcomponents-client-ga/quickstart.html
I imported everything, and was left with this error:
EntityUtils.consume(entity1); //X
} finally {
httpGet.releaseConnection(); //X
This portion of code is at two places in the tutorial, and errors occur at both.
Eclipse says for the first line:
"The method consume(HttpEntity) is undefined for the type EntityUtils."
Second line:
"The method releaseConnection() is undefined for the type HttpGet."
I'm pretty sure I downloaded every jar, transported them correctly, and imported everything. What is making the error? Thanks.
Here is what I have now. Edward, I used some of the code from your methods, but just put them into onCreate. However, this isn't working. A few seconds after I go from the previous activity to this one, I get the message that the app "has stopped unexpectedly".
I have a question about inputting my Strings into the website text fields: Do I use NameValuePairs of HttpParams? Here's my code, can you see what's wrong? Thanks.
package com.example.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class BalanceCheckerActivity extends Activity {
private final String LOGIN_URL = "https://someloginsite.com"; //username and password
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance_checker);
String username = getIntent().getExtras().getString("username");
String password = getIntent().getExtras().getString("password");
//Building post parameters, key and value pair
List<NameValuePair> accountInfo = new ArrayList<NameValuePair>(2);
accountInfo.add(new BasicNameValuePair("inputEnterpriseId", username));
accountInfo.add(new BasicNameValuePair("password", password));
//Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
//Creating HTTP Post
HttpPost httpPost = new HttpPost(LOGIN_URL);
BasicHttpParams params = new BasicHttpParams();
params.setParameter("inputEnterpriseID", username);
params.setParameter("password", password);
httpPost.setParams(params);
//Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(accountInfo));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
HttpResponse response = null;
InputStreamReader iSR = null;
String source = null;
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
iSR = new InputStreamReader(response.getEntity().getContent());
BufferedReader br = new BufferedReader(iSR);
source = "";
while((source = br.readLine()) != null)
{
source += br.readLine();
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
System.out.println(source);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_balance_checker, menu);
return true;
}
}
That mostly looks pretty good to me. I only saw one obviously wrong piece of code in it:
while((source = br.readLine()) != null)
{
source += br.readLine();
}
That's kind of a mess, and rather than try to untangle it, I'll just rewrite it.
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
String source = sb.toString();
Also, you shouldn't be doing network I/O from onCreate() or even from within your UI thread, since it can block for a long time, freezing your entire UI and possibly causing an "Application Not Responding" (ANR) crash. But for a simple test program, you can let that slide for now. For production code, you'd launch a thread or use AsyncTask().
Anyway, we're not really interested in building and debugging your program for you. Have you tried this code out? What was the result?
One final note: a login sequence like this is likely to return an authentication token in the form of a cookie. I forget how you extract cookies from an HttpResponse, but you'll want to do that, and then include any received cookies as part of any subsequent requests to that web site.
Original answer:
I think you've gotten yourself all tangled up. The Apache http client package is built into Android, so there's no need to download any jar files from apache.
I'm not familiar with EntityUtils, but whatever it is, if you can avoid using it, I would do so. Try to stick with the bundled API whenever possible; every third-party or utility library you add to your application increases bloat, and on mobile devices, you want to keep your application as light as possible. As for the actual "consume()" method not being found, that's probably a mistake in the documentation. They probably meant consumeContent().
The releaseConnection() call is probably only necessary for persistent connection. That's relatively advanced usage; I don't even do persistent or managed connections in my own code.
You haven't provided enough information to let us know what it is you're trying to do, but I'll try give you a reasonably generic answer.
There are many, many ways to transmit data to a server over the http protocol, but in the vast majority of cases you want to transmit form-encoded data via HttpPost.
The procedure is:
Create a DefaultHttpClient
Create an HttpPost request
Add headers as needed with setHeader() or addHeader().
Add the data to be transmitted in the form of an HttpEntity
Call client.execute() with the post request
Wait for and receive an HttpResponse; examine it for status code.
If you're expecting data back from the server, use response.getEntity()
There are many HttpEntity classes, which collect their data and transmit it to the server each in their own way. Assuming you're transmitting form-encoded data, then UrlEncodedFormEntity is the one you want. This entity takes a list of NameValuePair objects which it formats properly for form-encoded data and transmits it.
Here is some code I've written to do this; these are only code fragments so I'll leave it to you to incorporate them into your application and debug them yourself.
/**
* POST the given url, providing the given list of NameValuePairs
* #param url destination url
* #param data data, as a list of name/value pairs
*/
public HttpResponse post(String url, List<NameValuePair> data) {
HttpPost req = new HttpPost(url);
UrlEncodedFormEntity e;
try {
e = new UrlEncodedFormEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "Unknown exception: " + e1);
return null; // Or throw an exception, it's up to you
}
return post(req, e);
}
/**
* Post an arbitrary entity.
* #param req HttpPost
* #param data Any HttpEntity subclass
* #return HttpResponse from server
*/
public HttpResponse post(HttpPost req, HttpEntity data) {
try {
HttpClient client = new DefaultHttpClient();
req.setEntity(data);
HttpResponse resp = client.execute(req);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
Log.w(TAG,
"http error: " + resp.getStatusLine().getReasonPhrase());
return null; // Or throw an exception, it's up to you
}
return resp;
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol exception: " + e);
return null;
} catch (UnknownHostException e) {
return null;
} catch (IOException e) {
Log.e(TAG, "IO exception: " + e);
return null;
} catch (Exception e) {
// Catch-all
Log.e(TAG, "Unknown exception: " + e);
return null;
}
}

How to send request and response using http post url with body in android?

How to send HTTP POST request URL with Body and get responses using HTTP POST in android?
For Example
Thanks.
It varies depending of if you need to authenticate to see the webpage.
With or without the need of authenticating, you have to add the following permission in your Manifest to be able to access the webpage:
<uses-permission android:name="android.permission.INTERNET"/>
In your activity or class that makes the access, you can do the following:
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class YourClass
{
BufferedReader intro=null;
String url="Your Site URL?Your request body";
DefaultHttpClient cliente=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username","Your username"));
nvps.add(new BasicNameValuePair("password","your password"));
try
{
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = cliente.execute(post);
if(response.getStatusLine().getStatusCode()==200)//this means that you got the page
{
HttpEntity entity=response.getEntity();
intro=new BufferedReader(new InputStreamReader(entity.getContent()));
intro.readLine();
intro.close();
}
}
catch (UnsupportedEncodingException ex)
{
}
catch(IOException e)
{
}
}
Finally,take into account this:
-If you are doing authentication,take into account the fields "username" and "password" (inside BasicNameValuePair) may have another name,which dependes on the webpage
-With intro.readLine of the BufferedReader, you are reading the webpage as if you're reading the file, so you may want to parse in order to avoid showing html code

Categories

Resources