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!
Related
I want to send json data via stream to the server, but I struggle to make it work.
I have the following method:
String data = "{\"id\":\"2633\",\"f_name\":\"Test\",\"l_name\":\"Aplikace\",\"city\":\"Nymburk\",\"address\":\"Testovaci 123456789 xyz\",\"psc\":\"288 02\"}";
private String httpPost(String urlString, String data, String session_per) {
StringBuffer sb = new StringBuffer("");
String s1 = "";
try {
URL url = new URL(urlString);
String s2 = "";
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setRequestProperty("Cookie",session_per);
httpurlconnection.setRequestProperty("Authentication-Token", GlobalVar.KLIC);
httpurlconnection.setRequestProperty("Content-type", "application/json");
httpurlconnection.setAllowUserInteraction(false);
OutputStreamWriter outStrWrt = new OutputStreamWriter(httpurlconnection.getOutputStream());
outStrWrt.write(data);
outStrWrt.close();
String s3 = httpurlconnection.getResponseMessage();
//dataoutputstream.flush();
//dataoutputstream.close();
InputStream inputstream = httpurlconnection.getInputStream();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
int i;
while( (line = br.readLine()) != null) {
sb.append(line);
}
s1 = sb.toString();
}
catch(Exception ex)
{
ex.printStackTrace();
s1 = "";
}
return s1;
}
Can anyone tell me why this won't work? The cookies etc. are all correct. Did I miss something important? This is like the 6th method I am trying and I'm starting to get desperate :D
Thank you!
EDIT:
It succesfully connects and the server responds, but it doesn't update user data, as if the json didn't get to the server correctly.
If my Java code is correct there may be a server-side issue.
Try to use flush() method,you don't close this output stream before you read all bytes
outStrWrt.flush();
InputStream inputstream=httpurlconnection.getInputStream();
If you use Java 11, you can try to use HttpClient too.
E.g:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(new URI(urlString)).header("Cookie",session_per).header("Authentication-Token",GlobalVar.KLIC).header("Content-type","application/json").POST(HttpRequest.BodyPublishers.ofString(data)).build();
String datas=client.send(request,BodyHandlers.ofString());
return datas;
My program below stopped at the line:
InputStream is = conn.getInputStream();
Neither error message popped up nor any output displayed on the console.
I am running Eclipse Oxygen 4.7.0 on Red Hat Enterprise Linux Server release 7.4.
public static void solveInstance(String instanceName){
// solve a problem instance
try{
String query_url = "http://localhost:8807/scheduler";
// read Request to a JSON Object
JSONParser parser = new JSONParser();
JSONObject request = (JSONObject) parser.parse(new FileReader(instanceName));
// open connection
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// POST Request
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(request.toString());
osw.close();
// Get Response
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer response = new StringBuffer();
while(( inputLine = in.readLine()) != null )
{
response.append(inputLine);
}
in.close();
// Write response to a file
JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
String responseFile = /path_to_result/result.json;
FileWriter fileWriter = new FileWriter(responseFile);
fileWriter.write(jsonObj.toString());
fileWriter.flush();
fileWriter.close();
System.out.println("Solved" + instanceName);
}
catch(Exception e) {
System.out.println(e);
}
}
I noticed that the similar question is asked InputStream is = httpURLConnection.getInputStream(); stop working
but it was for Android and no solution was given there.
Does anyone have some idea on that? Do not hesitate to point out anything else wrong in my code.
Thanks a lot!
Your server isn't responding.
It would be wise to set a read timeout, with conn.setReadTimeout(5000) (say). Adjust the timeout as necessary.
Check response code
int response = connection.getResponseCode();
If you get 301 it means that your resource is redirected. Try to change URI from http to https.
It helped in my case.
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..
I have a data access object which calls a web service. In my browser I can hit the web service using a url and it is successful.
http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json
But when try to execute the code below in my data access object I get a 405 error saying method not allowed.
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Accept", "application/json");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
String jsonResponse = sb.toString();
out.close();
httpCon.disconnect();
Can someone help me with what might be wrong here?
Also maybe there is a better way to execute a web service to an external application and read the response using struts? Or do people think this method is okay?
thanks
If u are using GET method. Try the below code.
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = serviceRequest.DownloadString(new Uri(url));
Thanks for your ideas however non of them were quite right. I fixed the 405 using the code below...
String requestURI = "http://myserver:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
By calling httpCon.getOutputStream()); you're not sending a HTTP GET anymore, but a HTTP POST.
Note: This is under the assumption you end up getting the implementation provided by Sun. Which will change GET to POST for backwards compatibility.
On the first request it goes to the internet and retrieves the data. When I try it again, it just gives me the data that is already in the inputstream. How do I clear the cached data, so that it does a new request each time?
This is my code:
InputStreamReader in = null;
in = new InputStreamReader(url.openStream());
response = readFully(in);
url.openStream().close();
Recreate the URL object each time.
You can create a URLConnection and explicitly set the caching policy:
final URLConnection conn = (URLConnection)url.openConnection();
conn.setUseCaches(false); // Don't use a cached copy.
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
See The Android URLConnection documentation for more details.
HttpClient API might be useful
address = "http://google.com"
String html = "";
HttpClient httpClient = DefaultHttpClient();
HttpGet httpget = new HttpGet(address);
BufferedReader in = null;
HttpResponse response = null;
response = httpClient.execute(httpget);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
html = sb.toString();
You'll need to catch some exceptions