how to send file with httprequest in java? - java

how to send file with http request in java ?
i see question
Send image file using java HTTP POST connections
and
Upload files from Java client to a HTTP server
but them are too old question and not work any more .

A good example is given in Multi part File Upload example of Apache HttpClient
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup
The part that actually posts the file is
String targetURL = cmbURL.getSelectedItem().toString();
// add the URL to the combo model if it's not already there
if (!targetURL
.equals(
cmbURLModel.getElementAt(
cmbURL.getSelectedIndex()))) {
cmbURLModel.addElement(targetURL);
}
PostMethod filePost = new PostMethod(targetURL);
filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
cbxExpectHeader.isSelected());
try {
appendMessage("Uploading " + targetFile.getName() + " to " + targetURL);
Part[] parts = {
new FilePart(targetFile.getName(), targetFile)
};
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().
getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" + filePost.getResponseBodyAsString()
);
} else {
appendMessage(
"Upload failed, response=" + HttpStatus.getStatusText(status)
);
}
} catch (Exception ex) {
appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
Hope it is of some help to you.

Related

Microsoft Sharepoint online list all files in a folder

I want to get a list with all files and dirs in a dir located on a sharepoint
I do not have experience with REST api and I can not find this specific problem solved on google
I have the current code:
HttpURLConnection sharepoint = new LoginManager().login();
String siteURL = "https://confidential.sharepoint.com/something/"; //here <siteURL_path> is '/teams/SPdev/AlertsCount'
String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('TheFolder')";
//Send Request
InputStream in = sharepoint.getInputStream();
//Read the response.
String responseStr = "";
if (sharepoint.getResponseCode() == 302)
{
responseStr = "Folder read. ResponseCode: " + sharepoint.getResponseCode();
}
else
{
responseStr += "Error while reading folder, ResponseCode: " + sharepoint.getResponseCode() + " " + sharepoint.getResponseMessage();
}
System.out.println(responseStr);
Where LoginManager is something I did folowing this:
https://social.technet.microsoft.com/Forums/office/en-US/4c8d3696-1d41-44e3-897c-ac3c0b44f66a/share-point-online-authentication-using-java?forum=sharepointsearch

getting 401 when testing web api response time please assist

was hoping someone would assist me.
i have the below code, trying to test web api via http request on java but receiving a 401 unauthorised response. is there a way i can provide a password and confirm my authenticity to the system to get the response code and continue calculations of response time without receiving 401 response?
please see code below
public class readCSV {
public static void main (String [] args) throws IOException
{
String fileNames = "data.csv";
File file = new File(fileNames);// TODO read about file
try
{
Scanner inputStream = new Scanner (file);
inputStream.nextLine();
int count = 0;
long responseTime =0;
if (count > 0 ){ }
do
{
String data = inputStream.nextLine();// gets the entire string of data
String [] values = data.split(",");
System.out.print("Getting value: ");
count = count + 1;
System.out.print( count + " ");
System.out.print(values[1] + values[2] + values[3] + values[4] + values[5] + " ");
// open your connection
long start = System.currentTimeMillis();
URL url = new URL(values[0]);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
// System.out.print("Status: " + statusCode);
HTTPSTATUSPICKER pickStat = new HTTPSTATUSPICKER();
pickStat.statusCode(statusCode);
// send request, wait for response (the simple socket calls are all blocking)
long end = System.currentTimeMillis();
responseTime = end-start;
System.out.println(" ResponseTime = " + responseTime + " millis");
}
while(inputStream.hasNextLine());
}
catch (FileNotFoundException ex)
{
Logger.getLogger(readCSV.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
If you are getting 401 unauthorised , then its a clear case of Authorisation problem.
Check you token or any auth param you are passing while making REST call.
Also check your Controller/Rest service layer for auth management in REST(like basic auth, Oauth,or any other).

REST call returns 200 but no desired change due to POST

I have the below response from a REST call when used with postman.The Response code is 200 :
I am trying to write some code to make the REST call :
HttpHost httpHostTag = getMMCHost(prop);
System.out.println(httpHostTag);
//#SuppressWarnings("deprecation")
DefaultHttpClient httpclient = (DefaultHttpClient) verifiedClient(new DefaultHttpClient());
HttpGet httpostTag = verifiedGet(urlTagUpdate, Mmc_user, Mmc_password);
HttpResponse response = httpclient.execute(httpHostTag, httpostTag);
System.out.println(response.getParams());
int respCode = response.getStatusLine().getStatusCode();
System.out.println("response Code for Tag Update API Call : " + respCode);
String Code = Integer.toString(respCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//resultMsg = result.split(",")[0].split(":")[1];
resultMsg = result.split(",")[0].split("msg")[1];
System.out.println(resultMsg);
System.out.println("RESPONSE: " + result);
instream.close();
}
if (Code.equals("200") || Code.equals("202") || Code.equals("204")) {
System.out.println(resultMsg);
// return "RESPONSE : " + resultMsg;
} else {
return "Error : " + result;
}
} catch (Exception e) {
System.out.println("error in code ");
e.printStackTrace();
}
System.out.println("Tag Update to setenv.sh .................. This will take around 10 sec ");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// you probably want to quit if the thread is interrupted
}
return null;
}
In the split msg section above, I am getting errors. Nevertheless, even if I comment that section of the code,I am able to make the REST call. The call goes through and returns 200 as code. But it doesnot do any change as the REST call is supposed to do.
The REST url is correct as through POSTMAN it works perfect.
Any idea where I am making a mistake in the above code ?

How to sent XML file endpoint url in Restful web service

I need to send the request XML file to {url} as multipart form data. How this do in Restful web service. Before I use in there in,
RequestDispatcher rd = request.getRequestDispatcher("/file/message.jsp");
rd.forward(request, response);
But this isn't sent in specific {url}, How to sent it?
You can use the Jersey Rest Client to send your XML message as post request.
try {
Client client = Client.create();
WebResource webResource = client.resource(http://<your URI>);
// POST method
ClientResponse response = webResource.accept("multipart/form-data").type("multipart/form-data").post(ClientResponse.class, "<your XML message>");
// check response status code
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
// display response
String output = response.getEntity(String.class);
System.out.println("Output from Server .... ");
System.out.println(output + "\n");
} catch (Exception e) {
e.printStackTrace();
}
For Jersey Client you can find documentation here:
Jersey REST Client
WebResource
If you can do it (depends on your context), using a JAX-RS client is a solution.
Example with Apache CXF :
InputStream inputStream = getClass().getResourceAsStream("/file/message.jsp");
WebClient client = WebClient.create("http://myURL");
client.type("multipart/form-data");
ContentDisposition cd = new ContentDisposition("attachment;filename=message.jsp");
Attachment att = new Attachment("root", inputStream, cd);
client.post(new MultipartBody(att));
I don't think web service is best choice for you you can try native stream and then you can write the header and the body as you like here is sample code to explain my point
Socket socket=new new socket(InetAddress.getByName("stackoverflow.com"), 80);
// just the host and the port
Writer out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
out.write("POST http://" + HOST + ":" + port+ "/ HTTP/1.1\r\n");//here u can insert your end point or the page accepts the xml msg
out.write("Host: " + HOST + "/ \r\n");
out.write("Content-type: application/xml,text/xml\r\n");// Accept
out.write("Content-length: " + req.length() + "\r\n");
out.write("Accept:application/xml,text/xml\r\n");
out.write("\r\n");
// req the Request Body or the xml file to be sent
out.write(req);//
out.flush();`

send data through post from android to node.js?

I use nodejs as server and java(android) as client,i succes send data through post from android to node. but my problem when android send the data (string) consist of space and new line (enter) its received on node but the character was change,
for example,i send this string from android
Hello
I learn android
the string send to node and received,but i get this in node
Hello%0AI+learn+android
I use this code for send string to node in android.
public void btnOnClick(){
String text= URLEncoder.encode(editText.getText().toString(), "utf-8"); //I get from editText and convert to utf-8
sendToNode(text);
}
public void sendToNode(String text){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myDomain.com:8888/");
UrlEncodedFormEntity form;
try {
Log.i("kirim ke node isitextAsli ",text);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datanah",text));
form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
Log.i("HTTP Post", "Response from server node = " + response.getStatusLine().getReasonPhrase() + " Code = " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
Log.e("HTTP Post", "Protocol error = " + e.toString());
} catch (IOException e) {
Log.e("HTTP Post", "IO error = " + e.toString());
}
}
and I use this code for receive string in node
req.addListener('data', function(chunk) { data += chunk; });
req.addListener('end', function() {
console.log("from android :"+data); //result of data is Hello%0AI+learn+android
});
How i solve my problem?
please help,Thanks.
The string is URL-encoded, as you explicitly asked for in your code (and need for a regular POST). Decode it on the server.
To decode it on the server side, do:
var querystring = require('querystring');
querystring.unescape(data.replace(/\+/g, " "));
The following is the sample of encoding and decoding, YOU WANT TO DECODE IN THE SERVER PART
String encoded;
try {
encoded = URLEncoder.encode(input, "UTF-8");
System.out.println("URL-encoded by client with UTF-8: " + encoded);
String incorrectDecoded = URLDecoder.decode(encoded, "ISO-8859-1");
System.out.println("Then URL-decoded by server with ISO-8859-1: " + incorrectDecoded);
String correctDecoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Server should URL-decode with UTF-8: " + correctDecoded);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories