Json came null in Android Java - java

Error:
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
I have to send image to server with post method but I cant send. Json came to me null. There is my code:
if (method.equalsIgnoreCase("POST")) {
URL url_ = new URL(url);
String paramString = URLEncodedUtils.format(params, "utf-8"); // unused
HttpURLConnection httpConnection = (HttpURLConnection) url_.openConnection();
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
InputStream in = httpConnection.getInputStream();
OutputStream out = new FileOutputStream(picturePath);
copy(in, out);
out.flush();
out.close();
httpConnection.connect();
//Read 2
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line2 = null;
StringBuilder sb = new StringBuilder();
while ((line2 = br.readLine()) != null) {
sb.append(line2);
}
br.close();
json = sb.toString();
}
How can I send image to server?
Thanks..

Related

Problem uploading Image with JAVA to ActiveCollab API

I'm trying to upload an image with JAVA to a self-hosted ActiveCollab.
I have made a couple of tests and this one seems for me like the most solid of them by far. Anyway, when I try to run it, I get code 200-OK and an empty array as a response. .
public static void main(String args[]) throws IOException {
URL url = new URL("<SITE>/api/v1/upload-files");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "multipart/form-data");
c.setRequestProperty("X-Angie-AuthApiToken", "<TOKEN>");
JSONArray array = new JSONArray();
array.put("/test.png");
array.put("image/png");
OutputStream out = c.getOutputStream();
out.write(array.toString().getBytes());
out.flush();
out.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while (null != (line = buf.readLine())) {
response.append(line);
}
JSONArray message = new JSONArray(response.toString());
System.out.println(message);
}
In the API documentation I should get a filled json array as a response. Actually I don't know at what I'm missing.
Finally I solved it! As #StephanHogenboom said, the problem were in multipart/form-data, the parameters had to be introduced there and not via JSONArray. I didn't find so much information about how to work with multipart in java.net but at least I've found a deprecaded but functional way to the the job.
public static void main(String args[]) throws IOException {
URL url = new URL("<SITE>/api/v1/upload-files");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty("X-Angie-AuthApiToken", "<TOKEN>");
File file = new File("/1.png");
FileBody fileBody = new FileBody(file, "image/png");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);
c.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = c.getOutputStream();
multipartEntity.writeTo(out);
out.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while (null != (line = buf.readLine())) {
response.append(line);
}
JSONArray message = new JSONArray(response.toString());
System.out.println(message);
}
Actually it works for me, but if someone can give me ideas about how improve it would be great!

Json System.err: Unexpected character () at position 0. only from php

URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if (code==200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
String content = in.toString();
System.out.print(content);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result = (String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
When I have a host string like http://www.example.com/json.txt it all works fine, but when I have host string like www.example.com/index.php?data=data&data2=data2 I get the following error:
W/System.err: Unexpected character () at position 0.
I/System.out: 200java.io.BufferedInputStream#8bc189fpp = [0, 700, 250, 700]
My PHP output in browser looks fine, when I copy it to json.txt it also works fine.
I try to play with urlConnection POST, GET, RAW without luck.
Any ideas?
Problem was probly BOM in php json.
I do:
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
System.out.print(code);
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringWriter writer = new StringWriter();
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
result = result.substring(1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(result);
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
}
And it works.

Text file input using buffer reader, parse it and store in json array format using java and make one PUT api call

I have a text file where i am trying to fetch data one by one and store it in rri section with current time stamp under one PUT call but currently its fetching only one value or multiple request? Kindly help me to get through it. I will be sharing the text file and expected result in the comment section below.
File file = new File("DataToInput.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String urlString= "http://34.237.64.52 /v1/iot-hitoe-analytics/groups/0d98a4d3-207c-41e3-a943-363b73d58adf/raw-data";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
//conn.connect();
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("Accept", "application/json");
JSONObject Main = new JSONObject();
JSONArray alldata = new JSONArray();
JSONObject alldata1 = new JSONObject();
JSONObject metadata = new JSONObject();
metadata.put("sensorTypeId", sensorTypeId);
metadata.put("sensorId", sensorId);
metadata.put("sensorName", sensorName);
metadata.put("connectionMode",connectionMode);
JSONObject owner = new JSONObject();
owner.put("groupId", groupId);
owner.put("entityId", entityId);
JSONObject sensordata = new JSONObject();
JSONObject rawRri = new JSONObject();
JSONArray samples_rri = new JSONArray();
JSONObject samples1_rri = new JSONObject();
while ((line = bufferedReader.readLine()) != null) {
String[] fields = line.split(" ");
// System.out.println("fields size is "+fields.length);
// System.out.println("fields value is "+fields[0]);
stringBuffer.append(line);
stringBuffer.append("\n");
}
samples1_rri.put("rri",line);
samples1_rri.put("timestamp",System.currentTimeMillis());
samples_rri.put(samples1_rri);
rawRri.put("samples", samples_rri);
sensordata.put("rawRri", rawRri);
alldata1.put("metadata", metadata);
alldata1.put("owner", owner);
alldata1.put("sensordata", sensordata);
alldata.put(alldata1);
Main.put("alldata", alldata);
String payload = Main.toString();
ObjectMapper mapper = new ObjectMapper();
#SuppressWarnings("unused")
Object json = mapper.readValue(payload, Object.class);
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
System.out.println(indented);
/*OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(indented);
writer.close();*/
fileReader.close();
bufferedReader.close();
//System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
URLEncoder.encode(urlString,"UTF-8");
System.out.println("response codec: "+conn.getResponseCode());
// if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
// throw new RuntimeException("Failed : HTTP error code : "
// + conn.getResponseCode());
System.out.println("response received!!");
}
else {
System.out.println("response: "+conn.getInputStream());
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br1.readLine()) != null) {
System.out.println(output);
}

Encoding trouble: php api and java client program

I am sorry to post such a "noob question", but I can't solve my problem by myself.
I have a server-side script, written in php which returns different values, in this example all companynames which are stored in a MySQL DB.
-The column in the DB is encoded in UTF-8
-The php file is encoded in UTF-8
This is the server side script:
include_once('SQLHandler.php');
$SQLHandler = new SQLHandler();
if(isset($_POST['command'])){
$command = $_POST['command'];
switch($command){
case 'getCompanies':
echo utf8_encode('[["Test1"],["Test2"],["Test3"],["Test4"]]');
//echo json_encode( $SQLHandler -> getCompanies());
break;
}
}
it returns "[["Test1"],["Test2"],["Test3"],["Test4"]]".
However, when I want to analyze the returned String and parse it to an array (with json-simple library), the following occurs:
?[["Test1"],["Test2"],["Test3"],["Test4"]]
Unexpected token END OF FILE at position 0.
The Java Code is the following:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = rd.readLine()) != null){
System.out.println(line);
}
String jsonText = readAll(rd);
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(jsonText);
System.out.println(array);
System.out.println(array.toJSONString());
System.out.println(array.toString());
} catch(Exception e){
e.printStackTrace();
}
return null;
It is my first time working with java and json, so it is possible that I did a very easy to find error, but I would be very thankfull if you could point it out to me (and explain what I did wrong;))
Regards
Well, turns out it wasn't an encoding problem at all...
See my modified code:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String wholeLine = "";
String line;
while ((line = rd.readLine()) != null) {
wholeLine = wholeLine + line;
}
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(wholeLine);
for(Object obj : array.toArray()){
System.out.println(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
I forgot to supply "line" to the parse function and instead parsed the wrong variable ^^
Regards

I get EOFException while trying to get response from the server

I use a PrintWriter out object. I write data out.println(some data) and close it with a out.close
URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations) {
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
out.close();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null) {
//do something
}
br.close();
URL url = new URL(myurl);
URLConnection connection = null;
PrintWriter out = null; BufferedReader br = null; connection = url.openConnection(); connection.setDoOutput(true);
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()),true);
while(iterations)
{
//print data on writer
out.println(object);
}
//closig print writer
out.flush();
//Response from server
br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Get Exception in //this line EOF Exception
String temp;
while(temp = br.readLine() !=null)
{ //do something }
out.close();
Have a look at the code, you just had to put out.close instead of br.close at the end.

Categories

Resources