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);
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 am using following code to deserailze the JSON data from Url.
But My Error is:Value {"InvoiceNo":18} of type java.lang.String cannot be converted to JSONObject.My Json Like: "{\"InvoiceNo\":18}" Please Any one Help me.
private class LongOperation extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.1.2/Json/api/test"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject(responseText); // **Error on this line**
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = null;
try {
value = json.getString(key);
Toast.makeText(Billing.this, value + "",
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
textInvoice.setText(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("responseText", responseText);
return null;
}
}
Your String should not contain the character "\". If so, this is the cause of your problem.
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 have a json file that I am sending to the server as a POST but it has to be gzipped
I dont know how to do it
I found the potential solution here GZip POST request with HTTPClient in Java
but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)
EDIT: Here is how I get jsonAsBytes
public static byte[] stringToGZIPByteArray (String string) {
Log.d("string to be gzipped", string);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
};
}
}
return baos.toByteArray();
} // End of stringToGZIPByteArray
This is where I use that method
jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT, UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());
and this is sendGzippedJSONviaHTTP
public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {
if (httpClient == null) {
try {
httpClient = new HttpClientBuilder().setConnectionTimeout(10000)
.setSocketTimeout(60000) //
.setHttpPort(80)//
.setHttpsPort(443)//
.setCookieStore(new BasicCookieStore())//
.pinCertificates(res, R.raw.keystore, null) //
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Encoding", "gzip");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
reader.close();
json = sb.toString();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jsonObject;
} // End of makeHttpRequest
Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)
So, you can write:
HttpPost httpPost = new HttpPost(url);
post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
httpClient.execute(httpPost);
UPDATE:
this is the code from AndroidHttpClient:
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
throws IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}
should give you some insights
I need to send some data from my Android device to my server. I am doing this through JSON. I have implemented the JSON post on Android, and I am trying to do a mapping on the server side in order to retrieve that data. My problem is that I keep getting an empty string.
Android method used to send JSON:
private void sendJson(final String json, final String URL) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
try{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
client.execute(post);
}
catch(Exception e){
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Server-side method:
#RequestMapping(value = "/getLatestCalls", method = RequestMethod.POST)
public void getData(#ModelAttribute String json){
//... do something
}
The thing is that in this method my json String is "" every time. I have also tried using #RequestParam but with that it doesn't enter the method anymore. I have also tried with #ModelAttribute("json").
Can someone enlighten me a little here? Thank you in advance.
Here is the solution and it works fine.
server-side
#Controller
public class DataCollector {
#RequestMapping(value = "/clientdatacollector", method = RequestMethod.POST)
public #ResponseBody
void abc(Writer writer, #RequestParam("gpsdata") String gpsJSON) {
try {
// here is your jsonstring ;)
writer.write(gpsJSON.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client-side
public static void httptest() {
ArrayList<TravellingData> tdArray = new ArrayList<TravellingData>();
Gson gson = new Gson();
String jsonString = "";
for (int i = 0; i < 1; i++) {
tdArray.add(ObjectCreater.createMockTravellingDataObject());
}
jsonString = gson.toJson(tdArray);
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
try {
post = new HttpPost(
"http://localhost:8080/uygulama/clientdatacollector");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("gpsdata", jsonString));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = null;
try {
response = client.execute(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try using #RequestBody. It should work.