I am trying to recognize pictures with IQ Engines, and can't upload picture. Have anyone practice with using this api, or any ather to recognize pictures? I tryed to load bitmap, use Base64, load link to picture, but haven't always get img-this field is required. the last example of code is
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost("http://api.iqengines.com/v1.2/query/");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(path);
try {
// Add your data
String time = myTime();
String m = "api_key" + apiKey + "img" + file.getPath() + "json1"
+ "time_stamp" + time;
try {
sign = HmacSha1Signature.calculateRFC2104HMAC(m, secret);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
entity.addPart("api_key", new StringBody(apiKey));
entity.addPart("api_sig", new StringBody(sign));
entity.addPart("time_stamp", new StringBody(time));
entity.addPart("json", new StringBody("1"));
entity.addPart("img", new FileBody(file));
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
String result = EntityUtils.toString(entity1);
tv.setText(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
can anyone tell how it must be, or give working example of any other free api image recognition on android?
Related
I am developing the Google Drive API using the Restful API.
I need to upload a file and json body.
But when I try to upload with my java code, I was met error code from google-drive.
==> Invalid multipart request with 0 mime parts
Here is the Google-Drive's guide.
enter image description here
And Here is my code.
What is wrong in my code?
public int uploadFileToGoogleDrive(File file, Long acctId, String
accessToken, JSONObject json) {
HttpClient httpClient = new HttpClient();
PostMethod method = null;
Integer result = -1;
String boundary = "---------------------------" + System.currentTimeMillis();
try {
method = new PostMethod("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
method.setRequestHeader("Authorization", "Bearer " + accessToken);
method.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary );
Part[] parts = {new StringPart("",json.toString(),"utf-8"), new FilePart(file.getName(), file, null, "utf-8")};
//MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
httpClient.getHttpConnectionManager().closeIdleConnections(0);
result = httpClient.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream rstream = null;
rstream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
resultString += line;
}
}
System.out.println("##############################################\n" + json.toString() + "\n##############################################");
logger.debug(resultString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (ProtocolException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}finally {
method.releaseConnection();
}
return result;
}
}
multipart form uploads work just fine. Just don't specify a custom
Content-Type. Your content-type is going to fail otherwise because the
form-data boundary is determined by the XHR library internally. If you
want to use your Content-Type, then you will have to construct your
request separately and paste it as text in the "Raw" mode
look at this discussioin
and this one
I have the following problem..
when I hardcoded a url query which is like
example :
https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gslimit=5&gsradius=10000&gscoord=51.4451254|5.4731413&format=json
(check the link in your browser)
and I make the request to the server, I get the whole response in a string..
However when I make it dynamically I have to pass the "|" character, in URLEncoder.encode("|", "UTF-8") this format...
In that case, the response is only one element of what I want..
Is it something that it is missing to me?
Thanks in advance
protected String doInBackground(String... query) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = null;
// try {
HttpResponse execute = null;
try {
//String searchTerm = URLEncoder.encode(query[0], "UTF-8");
httpGet = new HttpGet(query[0]);
execute = client.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = execute.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(
content));
String s = "";
try {
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
The above part is my code.. the input query[0] is the url that I am requesting and it is similar to the link that I posted in the beginning.
If I hardcoded the url (set directly the the link), I have the response. My response is a string in json format. (for now I let it string)
If I make the query dynamically, for example like:
gsQuery = mainPage + "&gsradius=" + radius + "&gscoord=" + latitude + URLEncoder.encode("|", "UTF-8") + longtitude +"&format=json";
(encoded only the "|" character) it returns only the first element of my response.
I am trying to connect Bugzilla to java using j2bugzilla. But i can't
login to Bugzilla via following code. response is
{"version":"1.1","error":{"name":"JSONRPCError","message":"method is nothing.","code":100300}}. Can anyone point where the issue ?
static void callBugzilla() {
BugClass bugObj = new BugClass();
bugObj.setComponent("News Reader");
bugObj.setProduct("MR7");
bugObj.setSummary("this is a test summary");
bugObj.setVersion("1.0");
HttpParams httpParameters = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParameters, 10000);
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
// HttpConnectionParams.setSoTimeout(httpParameters,
// SO_TIMEOUT);
DefaultHttpClient httpclient1 = new DefaultHttpClient(httpParameters);
HttpPost httpPostRequest = new HttpPost(
"http://bugzilla.mycompanyname.org/bugzilla/jsonrpc.cgi?method=User.get&Bugzilla_login=login&Bugzilla_userName=abcd.kg#companyname.in&Bugzilla_password=123456");
StringEntity entity = null;
try {
entity = new StringEntity(new Gson().toJson(bugObj));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(new Gson().toJson(bugObj));
entity.setContentType("application/json");
// Set HTTP parameters
httpPostRequest.setEntity(entity);
System.out.println("entity:" + httpPostRequest.getEntity());
// Pass Profile to Server and collect response
String uploadResponse = null;
try {
HttpResponse resp = httpclient1.execute(httpPostRequest);
System.out.println("resp:" + resp.getStatusLine());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use the following code to connect to the Bugzilla.
BugzillaConnector conn = new BugzillaConnector();
conn.connectTo("http://bugzilla.mycompanyname.org/bugzilla/", "userName", "password");
LogIn logIn = new LogIn("userName", "password");
conn.executeMethod(logIn);
and meven dependency is
<dependency>
<groupId>com.j2bugzilla</groupId>
<artifactId>j2bugzilla</artifactId>
<version>2.2</version>
</dependency>
I'm making a google login through GoogleTransport and ClientLogin.
private final GoogleTransport transport = new GoogleTransport();
private final ClientLogin authenticator = new ClientLogin();
Then I'm accessing the Picasa web api.
transport.setVersionHeader(PicasaWebAlbums.VERSION);
transport.applicationName = "google-picasaandroidsample-1.0";
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
authenticator.authTokenType = PicasaWebAlbums.AUTH_TOKEN_TYPE;
authenticator.username = StaticVariables.USER_NAME+StaticVariables.USER_DOMAIN;
authenticator.password = StaticVariables.USER_PASSWORD;
try {
authenticator.authenticate().setAuthorizationHeader(transport);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://picasaweb.google.com/data/feed/api/user/default");
request.execute();
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above is working fine.
Now I want to set a POST request. But buildPostRequest() method does not support any String parameter. So, unable to post any data at the URL. How to achieve it? Please help.
You may use HttpPost with NameValuePair
private boolean sendData(ArrayList<NameValuePair> data) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then create your Name Value pairs in a different method as
private ArrayList<NameValuePair> setupData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(USERID, SAMPLE_USER_ID);
nameValuePairs.add(new BasicNameValuePair(USERNAME, SAMPLE_USER_NAME));
return nameValuePairs;
}
Atlast call the send data method in an AsyncTask or Intent service as sendData(setupdata())
Data in a post request is usually sent in the body of the request.
I'm trying to use httpost to get data from our WCF webservice
If the webservice function is without params , something like List getAllMessages()
I'm getting the List in json, no problem here
The tricky part is when the function needs to get argument
let's say Message getMessage(string id)
when trying to call this kind of functions I get error code 500
The working code is:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
this code works great for functios without arguments..
I took this code and changed it to:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The function header in thr webservice is:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
Anyone can see what am I missing?
Thanks, I'm breaking my head over this one.
List isn't json,
try
String data = "{ id : \"" + id + "\" }";
Don't forget to set Content-Length to data.length.