POST request using form-data in body with core java, getting bad request - httpurlconnection

I have written an core java code to post call with form-data(always pdf) along with Auth but i am always getting bad request.enter image description here
public class POSTAPIClientSucessFile2 {
public static void main(String[] args) throws IOException {
try {
String boundary = "";
final String LINE_FEED = "\r\n";
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String authData = "Bearer 3AAABLblqZhAmXYU1afunO0RBkBBOxDcE0elkSXa6WmNorjjNNGoWjQF5f_mnl21GVK4bOGjsIzqNNB1ZLLLZol--21hmnI1w";
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL("https://api.na3.echosign.com/api/rest/v6/transientDocuments");
System.out.println("URL : " + url.toString());
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.addRequestProperty("Authorization", authData);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
String fileName = "C:/delete/test.pdf";
//String fieldName = "File";
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"File\"; filename=\"/C:/delete/test.pdf\"").append(LINE_FEED);
writer.append("Content-Type: application/pdf").append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
int responseCode = ((HttpURLConnection) httpConn).getResponseCode();
System.out.println("responseCode --> "+responseCode);
System.out.println("response msg--> "+((HttpURLConnection) httpConn).getResponseMessage());
System.out.println("response --> "+((HttpURLConnection) httpConn).toString());
FileInputStream inputStream = new FileInputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
always getting bad request even by changing the content-type
enter image description here

Related

POST multipart/form-data contents out of order

I am trying to build a web server using java sockets, everything is fine except when the browser sends POST request with file attached, when the request is received the content of the file is out of order , the file sent was txt file with line numbers when received the line numbers were out of order. is there any way I can avoid this I want ordered data (see pic 99522 is followed by 99712) THANKs
public class Server{
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
while(true) new Thread(new Client(server.accept())).start();
}
}
class Client implements Runnable {
Socket client;
OutputStream os = new FileOutputStream(new File("File12"));
InputStream in;
OutputStream out;
static ArrayList<Socket> clients = new ArrayList<Socket>();
String index;
String response;
Client(Socket client) throws IOException {
String listOfFiles = "<ol>";
this.client = client;
in = client.getInputStream();
out = client.getOutputStream();
clients.add(client);
for (File file : new File(".").listFiles()) if (file.isFile()) listOfFiles += "<li>" + file.getName() + "</li>";
listOfFiles += "</ol>";
index = "<!DOCTYPE html><html><body><h1>" + new Date() + "</h1><hr>"+listOfFiles+"<form id='upload' enctype='multipart/form-data' method='post' action='/upload'><input id='fileupload' multiple name='myfile' type='file' /><input type='submit' value='submit' id='submit' /></form></body></html>";
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:"+index.length()+"\r\n" +
"\r\n" +
index;
}
public void run() {
try {
String msg = "";
byte buffer[] = new byte[32*1024];
int read = in.read(buffer);
while(read != -1){
msg = new String(buffer);
System.out.println(msg);
if(msg.startsWith("POST")){
System.err.println("RAN IN POST");
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Content-Type: text/plain\r\n".getBytes());
out.write(("Content-Length:"+ 4 +"\r\n").getBytes());
out.write("\r\n".getBytes());
out.write("done".getBytes());
}
if(msg.startsWith("GET")){
String path = msg.substring(msg.indexOf("/"), msg.indexOf("HTTP")).trim();
if(path.equals("/")) out.write(response.getBytes());
else {
String fileName = path.substring(1);
fileName = URLDecoder.decode(fileName,"UTF-8");
System.out.println(fileName);
File file = new File(fileName);
if(file.exists()){
System.out.println(file.getName() + " " + file.length());
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(("Transfer-Encoding: chunked\r\n").getBytes());
out.write("Content-Type: application/octet-stream\r\n".getBytes());
out.write(("Content-Disposition: attachment; filename=\""+file.getName()+"\"\r\n").getBytes());
out.write("\r\n".getBytes());
try{
Files.copy(Paths.get(file.getPath()) , out);
}catch(Exception e){
break;
}
}else System.out.println("file not existes");
}
}
out.flush();
os.close();
read = in.read(buffer);
}
System.err.println("closing scoket");
out.close();
in.close();
client.close();
clients.remove(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ALL right found the bug I am not clearing the buffer hence it appears again

Parsing JSonObject response by Rest client java

I have written the RestClient to call the rest service and then parse the response. I use this:
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
jObj = new JSONObject(json);
return jObj;
I m getting response like this :
{\"r\":{\"#status\":\"ok\",\"#st\":\"ok\",\"#call_id\":\"8410e\",\"method\":\"notification\",\"notification\":" +
"{\"#status\":\"true\",\"n\":{\"objects\":{\"#totalClassCount\":\"35\",\"#totalTestCount\":\"0\",\"#totalContentCount\":\"0\"," +
"\"#totalAssignmentCount\":\"5\",\"#totalOverdueCount\":\"16\",\"#totalCourseCount\":\"97\",\"#lastClassTime\":\"01-01-1753 12:00:00\"," +
"\"#lastTestTime\":\"01-01-1753 08:00:00\",\"#lastContentTime\":\"09-01-2015 02:52:30\",\"#lastAssgnTime\":\"01-01-1753 08:00:00\"," +
"\"#lastOverdueTime\":\"01-01-1753 12:00:00\",\"#lastCourseTime\":\"09-01-2015 02:52:30\",\"#lastCommentTime\":\"14-12-2015 03:48:55\"," +
"\"flag\":\"1\",\"object\":[{\"#type\":\"3\",\"content\":{\"#contentid\":\"137\",\"ntype\":\"1\",\"sime\":\"9 months ago\"," +
"\"title\":{\"#cdata-section\":\"xlsx icon file\"},\"courseid\":\"95137\",\"sid\":\"1976\",\"subid\":\"0\",\"coursetype\":\"1\",\"contentsize\":" +
"\"0\",\"csid\":\"2\",\"contenttypeid\":\"6\",\"contentviews\":\"0\",\"totalslides\":\"16\",\"iscreator\":\"0\"}}}]}}}}}
Could you please help me how i can parse it?
Thanks,
itin
The code for converting to JSON is not exactly right - Try JSONObject. you can do better as shown below.
if (httpEntity != null) {
String resultString = EntityUtils.toString(httpEntity);
// parsing JSON and convert String to JSON Object
JSONObject result = new JSONObject(resultString);
return result;

Get body of Bad Request httpURLConnection.getInputStream()

I've been working on a portlet that calls Rest API. When the API is called and the requested data doesn't exist, it returns an appropriate error message in JSON format (with Bad request http code - 400), and if the id exists, it returns the requested data in json (with code 200).
How can I get the body of response (that contains error description) because invoking httpConn.getInputStream() method throws exception in case the response is bad request error.
Code:
HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
builder.append(output);
return builder.toString();
}else
here should catch the error message. :)
In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().
you can get body of Bad Request in HttpURLConnection using this code :
InputStream errorstream = connection.getErrorStream();
String response = "";
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));
while ((line = br.readLine()) != null) {
response += line;
}
Log.d("body of Bad Request HttpURLConnection", "Response: " + response);
Use Apache Httpclient:
String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null)
result.append(line);
System.out.println(result);

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

send push via urban airship using their web service (java)

I have gone through the post
The code works fine for me. i need to do this using java, i tried using the HttpURLConnection and the javax.xml.rpc.Service but no luck.
I need to know how to do the implementation using java.
Solved it.
pushClient class:
public static void main(String[] args)
{
try
{
String responseString = "";
String outputString = "";
String username = "Application Key";
String password = "Application secret";
Authenticator.setDefault(new MyAuthenticator(username,password));
URL url = new URL("https://go.urbanairship.com/api/push/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\"APID\"]}";
byte[] buffer = new byte[postdata.length()];
buffer = postdata.getBytes("UTF8");
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestProperty("Content-Length",String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null)
{
outputString = outputString + responseString;
}
System.out.println(outputString);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
MyAuthenticator class:
private String user;
private String passwd;
public MyAuthenticator(String user, String passwd)
{
this.user = user;
this.passwd = passwd;
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, passwd.toCharArray());
}