Live mjpeg video stream from server to android - android

I am trying to fetch mjpeg live video stream from server to android.I read this answer.it is very helpful to me.It works with this demo url.But, In my video stream it asking for username and password.
To set url into MjpegView:
setContentView(mv);
mv.setSource(MjpegInputStream.read(URL));
MjpegInputStream:
public static MjpegInputStream read(String url) {
HttpResponse res;
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
res = httpclient.execute(new HttpGet(URI.create(url)));
return new MjpegInputStream(res.getEntity().getContent());
} catch (ClientProtocolException e) {
} catch (IOException e) {}
return null;
}
As in web browser whenever i open my server link..it asking for 'password' & 'username'.so
where to put params in this read() ? and also want to know if my live video is in H.264
format. then how can i convert it into MJPEG format?Also its speed is very slow and not smooth.how to improve it?
Thanks in Advance!!

You are promted for a login because the webcam is password protected. Normally with webcams you have to pass the username and password as part of the URL. eg. username:password#ip.address.or.dyndns.com:8085/folder/stream.jpg?size=large where the number at the end is the port number.

it's been a time... but to login:
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget2 = new HttpGet(url);
httpget2.addHeader("Authorization","Basic " + Base64.encodeToString((USERSTRING:PASSWORDSTRING).getBytes(),Base64.DEFAULT));
res = httpclient.execute(httpget2);
return new MjpegInputStream(res.getEntity().getContent());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

Android - Sending Images to server generate huge HTTP request

I'm currently sending an image to my server by encoding it into a base64 string like this: https://gist.github.com/fabdarice/a4006a97171cc415892e
However, when I'm looking at the HTTP POST request, I'm seeing something like this :
{"login"=>"Jerem", "mobile_upload_file"=>"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAQ4BDgDASIA\nAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA\nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3....................................}
This goes on for a while, (around 1 millions characters) and it seems to make my server laggy.
I was wondering if this is a normal behavior to see that amount of characters sent? If not, how am I supposed to implement the process of sending an image to a server?
Thanks for your help
You can send image in FileBody by Multipart entity like this...
public String sendMultipartRequestToServer(BusinessDataObject dataObject,String url) {
String responseString=null;
HttpResponse response;
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpConnectionParams.setConnectionTimeout(client.getParams(),50000);
MultipartEntity multipartEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
multipartEntity.addPart(KEY_EMAIL,new StringBody(dataObject.getEmail()));
multipartEntity.addPart(KEY_PASSWORD, new StringBody(dataObject.getPassword()));
multipartEntity.addPart(KEY_IMAGE,new FileBody(new File(Here your image path on your memory)));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Setting parameter to post method
post.setEntity(multipartEntity);
try {
response=client.execute(post);
InputStream inputStream=response.getEntity().getContent();
responseString=convertStreamToString(inputStream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
If you will not find the class MultipartEntity .Then you have to add HttpMime.jar in your project .It is the best way to send images so far i know here no need to convert image in Base64.You can just pass the url of selected image to FileBody.

Android SSL Certificate Authentication (with the Android KeyChain API) to a WCF Service

I have big problems with getting the certificates running under android.
I have an android client which connects to a WCF-Service.
I think the problem is, that the certificates are not transfered. I get an error message:
403 forbidden (in the response). I really hope you can help me.
=> in my android client
In internet explorer, it works just fine => status 200
I found this article:
http://android-developers.blogspot.de/2012/03/unifying-key-store-access-in-ics.html
"A common use of the private key is for SSL client authentication. This can be implemented by using an HttpsURLConnection with a custom X509KeyManager that returns the PrivateKey retrieved from the KeyChain API. The open source Email application for ICS uses KeyChain with an X509ExtendedKeyManager. To learn more, have a look at the source code (in SSLUtils.java)."
I have checked out the SSLUtils class and I am trying to use it.
Here is some code:
private void setHttpsAdvanced() {
HostAuth ht = new HostAuth();
ht.mPort = 443;
ht.mClientCertAlias = "jensZert";
HttpParams params = getHttpParams();
MyThreadSafeClientConnManager ccm = MyThreadSafeClientConnManager
.newInstance(params, true, 443);
try {
MyThreadSafeClientConnManager.makeScheme(true, false,
ht.mClientCertAlias);
ccm.registerClientCert(getApplicationContext(), ht);
// checkCertificate(ht.mClientCertAlias);
} catch (CertificateException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
}
this.httpclient = new DefaultHttpClient(ccm, params);
connectionInfo = this.getConnectionInfo();
this.url = String.format("%1$s://%2$s/%3$s/%4$s",
connectionInfo.Protocol, connectionInfo.ServerName,
connectionInfo.WebserviceName, connectionInfo.Path);
httpGet = new HttpGet(url);
}
private String callTheWebserviceCertificate() {
this.setupClient();
String result = "";
HttpResponse response = null;
try {
response = (HttpResponse) this.httpclient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
result = e.getMessage() + "\n";
for (StackTraceElement el : e.getStackTrace()) {
result += el.toString() + "\n";
}
Log.d(TAG, result);
}
return result;
}
greetings,
jens

Android parse Json with chinese characters

I got a valid Json string(at least every onlinevalidator I tried says so) which contains some chinese characters.
The json string is the following:
{"title":"\u8981\u805e--\u83ef\u723e\u8857\u65e5\u5831","url":"http://cn.wsj.com","desc":"\u300a\u83ef\u723e\u8857\u65e5\u5831\u300b\u4e2d\u6587\u7db2\u7d61\u7248\u6700\u65b0\u8ca1\u7d93\u8981\u805e","imageUrl":null,"lastUpdate":"1327588937","items":[{"title":"\u4e16\u8cbf\u7d44\u7e54\u7e3d\u5e79\u4e8b\ufe55\u4eba\u6c11\u5e63\u5e63\u503c\u88ab\u4f4e\u4f30\ufe50\u4f46\u4f4e\u4f30\u7a0b\u5ea6\u4e0d\u660e","desc":"\u4e16\u754c\u8cbf\u6613\u7d44\u7e54\u7e3d\u5e79\u4e8b\u5e15\u65af\u5361\u723e\uff0e\u62c9\u7c73\u9031\u56db\u8868\u793a\ufe50\u4eba\u6c11\u5e63\u532f\u7387\u88ab\u660e\u986f\u4f4e\u4f30\ufe50\u4f46\u4f4e\u4f30\u7a0b\u5ea6\u9084\u4e0d\u6e05\u695a\u3002","url":"http://cn.wsj.com/big5/20120126/BCHc-20120126WR182711424.asp?source=rss","pubdate":null}]}
Now when i Parse the JsonString in Android via new JsonObject(jsonString) I only got some squares instead of characters.
Why cant android handle this json string?
Any help would be apreciated.
If anyone would like to have the server Ressource, it can be found under:
// edit
url removed
public static String test(){
String testResult= "";
try {
HttpGet get = new HttpGet("http://xxxxx");//edit url removed.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(result);
if(!obj.isNull("title")){
testResult= obj.getString("title");
Log.d("Test","Test1:"+ testResult);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return testResult;//
}
and Then TextView.setText(testResult);
It works for me.
it's Traditional Chinese String:"要聞--華爾街日報"
May be your ROM has no Traditional Chinese font????
When you receive your JSON, you may have to decode the UTF-8 result when you're building your result. Have a look at utf8 decoding. Something similar to this, but with JSON

Problems running deployed apps on Google AppEngine

I have written a web application to run on Google AppEngine using the Restlet framework, communicating using json with web clients. Those work as expected. However, one specific resource written to provide response to an Android client doesn't work when accessed through Android. However, it does work when accessed through a web browser (I do not send the request parameters from the browser and thus get a 400 which is ok in this case).
This code works when running on the DevAppServer:
public class PlayResource extends ServerResource {
private final float SCOREBASE = 1000.0F;
#Get
#Post
public JsonRepresentation play() {
try {
JsonRepresentation rep = new JsonRepresentation(getRequestEntity());
JSONObject inputJson = rep.getJsonObject();
JSONObject outputJson = new JSONObject();
String country = inputJson.optString("country");
outputJson.put("country", doSomething("country",country));
......
......
return new JsonRepresentation(outputJson);
} catch (IOException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_REQUEST));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
} catch (JSONException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_FORMAT));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
}
and the client Android device is running this code:
Client client = new Client(Protocol.HTTP);
try {
JsonRepresentation requestJSON = new JsonRepresentation(new JSONObject()
.put("country", country.trim())
);
Request req = new Request(Method.GET,"http://****.appspot.com/resource/play",requestJSON);
Response resp = client.handle(req);
String res = resp.getEntity().getText();
JSONObject resultJSON = new JSONObject(res);
Running this request just hangs the Android client, the server doesn't write any log messages whatsoever suggesting the request doesn't arrive there.
It seems that it's more a Appengine/Java issue than an android issue, but...let's try something else:
instead of using Client and the stuff u are using, first just try to see what the server responds to the simplest connection (as you do in a web browser):
URL url;
try {
url = new URL("http://yourappid.appspot.com/resource/play");
String content = (String) url.getContent();
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it works and you get your expeted 400, if so...try to send an httppostrequest with the data...like this:
HttpClient client = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpPost("http://yourappid.appspot.com/resource/play");
//set the content type to json
httpRequest.setHeader("Content-Type", "application/json");
//get and work with the response
HttpResponse httpResponse = client.execute(httpRequest);
Let me know if the answer was useful

Why doesn't HttpClient work but HttpUrlConnenction do when posting data to form

I'm building an android app which should perform a GET on my site to get two cookies and then perform a post to the same site with these cookies.
As mentioned I start of with the GET and I'm using org.apache.http.client.HttpClient to perform this operation.
String requiredCookies = "";
HttpContext localContext = null;
System.out.println("------------------GET----------------------");
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("www.mysitegeturl.com");
//Creating a local instance of cookie store.
CookieStore cookieJar = new BasicCookieStore();
// Creating a local HTTP context
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);
HttpResponse response;
try {
response = httpClient.execute(get, localContext);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
//Do this so that Java.net impl should work
List<Cookie> cookies = cookieJar.getCookies();
for (int i = 0; i < cookies.size(); i++) {
requiredCookies += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("------------------GET-END---------------------");
So far so good. Don't mind the requiredCookies line yet, it will be used in the Java.net impl since I can't get the HttpClient one to work =(.
Let's take a look at the non working HttpClient Post part.
System.out.println("------------------HttpClient - POST----------------------");
HttpPost post = new HttpPost("www.mysiteposturl.com");
//Params
HttpParams params = new BasicHttpParams();
params.setParameter("foo", "post");
params.setParameter("bar", "90");
params.setParameter("action", "search");
post.setParams(params);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
HttpResponse response2 = httpClient.execute(post, localContext);
System.out.println(response2.getStatusLine());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
What happens now is that I perform a POST with the localContext where the cookies are stored. This doesn't work. I get a HTTP/1.1 401 No session. Since I had no luck with this I tried another approach(java.net.HttpURLConnection). Remember I still use the same GET part
URL url = new URL("www.mysiteposturl");
HttpURLConnection connection = null;
String dataString = "bar=90&foo=post&action=search";
try {
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie", requiredCookies);
//Set to POST
connection.setDoOutput(true);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(dataString);
writer.flush();
writer.close();
connection.connect();
if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {
System.out.println(connection.getContent().toString());
} else {
System.out.println("Error");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------POST END---------------------");
And VIOLA a 200 is displayed and everything works like a charm. What do you guys think? Could someone please provide me with an answer because I can't figure it out.
The problem appears to be that you have two different host names in the setup. This will cause HTTP Client to not send cookies for a different host. You could try changing the domain of the cookies in the cookie store, or using the same host for GET and POST. Additionally you could manually add the cookies to the headers in HTTP Client as you did in the HttpURLConnection example.
I guess it was a mistake that you used two completely different domains for your two requests — i.e. you were trying to mask your real URL? If not, then that's why you're not getting any cookies. If were just trying to mask your URL, well that's why example.com exists. :)
Alternatively, and this is completely off the top of my head from code I wrote last week — it worked fine across multiple GETs, POSTs and subdomains:
DefaultHttpClient httpClient = new DefaultHttpClient();
CookieStore cookieJar = new BasicCookieStore();
httpClient.setCookieStore(cookieJar);
i.e. I'm explicitly using a DefaultHttpClient, which I believe has those extra get/setters for the cookie store. I don't think I used any context objects either.

Categories

Resources