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.
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've such a weird error:
Im trying to parse json objects from a url. Which works perfect for example this is the json data:
{"type":"result","rid":"djoezradio",
"data":[{
"title":"Webradio",
"song":"Test",
"track":{
"artist":"Test",
"title":"Test",
"album":"",
"Test":422,
"id":423,
"playlist":{
"id":14,"title":"reggae"
},
"imageurl":"http:\/\/example.com\/static\/example\/covers\/nocover.png"},
"bitrate":"128 Kbps",
"server":"Online","autodj":"Online","source":"Yes","offline":false","listeners":1,
"maxlisteners":500,"reseller":0,"serverstate":true,"sourcestate":true,
"sourceconn":true,"date":"Dec 14, 2013",
"time":"02:13 PM","url":"http:\/\/example.com\/"}]}
This is my code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
JSONObject jObject = new JSONObject(line);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When i do getString("playlist") for example, it just works well, it will return id:14 etc.
The ONLY thing which doesn't work is the object imageurl...
When i want to parse this, it just returns null, while its just there!
Any ideas?
Is there some reason? Its becouse its a .jpeg?
Pleas share, im really stuck.
Try this.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while((line=in.readLine())!=null)
{
builder.append(line);
}
String JSONdata = builder.toString();
Log.i("JsonData",JSONdata);
JSONObject jObject = new JSONObject(JSONdata);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
JSONObject jObject = new JSONObject(JSONdata);
JSONArray jdata = jObject.getJSONArray("data");
JSONObject job = jdata.getJSONObject(0);
JSONObject jObjt = job.getJSONObject("track");
String temp = jObjt.getString("imageurl");
Log.e("rid",temp);
I am learning Android now and I am working on how to fire a request and receive a result from server. What I am doing is
// Button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String testURL = "http://djs-corner.appspot.com/getClosestClubs?lat=40.7600624&lon=-73.98558";
// Create http GET method
HttpClient client = new DefaultHttpClient();
// Create http GET method
HttpGet getTest = new HttpGet(testURL);
// Fire a request
try {
HttpResponse response = client.execute(getTest);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);
Log.e("RESULT", result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ClientProtocolException is ", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("IOException is ", e.toString());
}
}
});
String convertStreamToString(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
return sb.toString();
}
The result I am getting back is just partial of original result.Please look at the image at here. If we take a look at data from the above url, we can see that some of the data are chopped down.
What i am doing wrong at here.
I'm trying to let my users be able to report small errors my android application automatically catches to my server. It's nothing big, just a small text box and send button.
It's supposed to send 3 strings (error, optional user description, and time) to a file on my website made specifically to capture those errors. The thing is, I have absolutely no idea how to do so. I only know how to let my application read info from my website but not the other way around.
Do I have to have a special script on my website? Are JSON Strings necessary? I need the string to be saved there. (Not temporarily)
I'm a bit of a newbie so any help is appreciated. Thanks!
- There has to be a script running on your server, eg: php script.
- Its actually a web-service published on the server so that a client can access it.
- Then you will need to do a HTTP Post to the Server, its better to use NameValuePair along with it to send the data.
This is my code for doing HTTP POST:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now", sb + "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method " + sb.toString());
return sb.toString();
}
//////////////////////////// Edited Part ///////////////////////////////////
Server side php code:
<?php
require_once(ROOT.'/lab/lib/xyz_api_int.php');
try {
//setup the sdk
$api = YumzingApiInt::_get(
Config::get('api_int','url'),
Config::get('api_int','key'),
Config::get('api_int','secret')
);
//connect to the api
$api->connect();
//check our token
echo $api->getToken();
} catch(Exception $e){
sysError($e->getMessage());
}
You just need to post values by http to a php script on your server that will save those values in your file or a database.
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?