How to upload data using POST-query? - java

I have following problem: I'm developing the application which need to authorize on server and upload data from my mobile into it. The server side is ready and works correctly. So, for authorizing I use the following code:
URL url = new URL(VALIDATING_URL);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
PrintWriter out=new PrintWriter(connection.getOutputStream());
out.print(POST_QUERY_EMAIL+email);
out.print("&");
out.print(POST_QUERY_PASS+password);
out.print("&");
out.print(POST_QUERY_CHANNEL+channel);
out.close();
Scanner in=new Scanner(connection.getInputStream());
StringBuilder result=new StringBuilder();
while (in.hasNextLine()) {
result.append(in.nextLine());
result.append("\n");
}
in.close();
It works correctly, and the application will get needed result if I enter correctly data. So, now I need to upload data into server using POST-query, but I don't know how I can do it. Using HTML forms, video is usually uploaded using 'userfile' variable and will be got from $_FILES array in PHP scipts. How can I upload do it from Java? Can I just print data into PrintStream from InputStream?
Thank you, I hope you can help me

Try this,
public void postData() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.xyz.com");
List<NameValuePair> list = new ArrayList<NameValuePair>(1);
list.add(new BasicNameValuePair("name","ABC");
httppost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse r = client.execute(httppost);
}

I would suggest reading this. It shows you how to do a POST with URLConnection and explains what's going on.

Related

HTTP POST Request with Json body giving error code 400

I'm trying to send a Json format in body of POST request in java.
I tried a lot of codes from the internet and StackOverflow, but nothing is working.
I keep getting java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8080/engine-rest/message.
After trying a lot on Postman i noticed it only accepts Json format body, i tried using json libraries like Gson, yet still nothing worked.
Any ideas on how to fix my code? Again I did try to copy a lot of codes from the internet so please don't send me a similar title stackoverflow thread and call the question repetitive.
Thank you in advance.
public class PostRequest {
FileWriter myWriter;
URL url;
public void sendPost(String Url) throws IOException {
String name = "{\"messageName\": \"URLFound\", \"businessKey\": \"3\"}";
try {
myWriter = new FileWriter("C:\\Users\\test\\Desktop\\camunda test save\\Post.txt");
url = new URL ("http://localhost:8080/engine-rest" + Url);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
OutputStream os = http.getOutputStream();
byte[] input = name.getBytes("utf-8");
os.write(input, 0, input.length);
BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuffer response = new StringBuffer();
while ((in.ready())) {
response.append(in.readLine());
}
in.close();
//Writing result on .txt
myWriter.append(response.toString() + "\n" +url);
}
catch(Exception e){
myWriter.append(e.toString());
}
myWriter.close();
}
}
How about using this client project?
https://github.com/camunda-community-hub/camunda-rest-client-spring-boot/
For example:
https://github.com/camunda-community-hub/camunda-rest-client-spring-boot/blob/dce6bd777e3350dd30286311c5351aa9460a34f4/examples/example/src/main/java/org/camunda/bpm/extension/rest/example/standalone/client/ProcessClient.java#L98
Java cant create an object from your json. Check if all fields are sent in the request body of the java class that is expected on the backend side.

Android: steps to upload a file to server over http

Im since a week trying to upload a file over http to a server. I have found hunderts of tutorials but I cant work with them. Some classes and methods are depricated and so on. Now I want to do it by my own but I need to know the steps.
Right know I have an image on my phone that I want to upload. What are the steps I need to do?
Convert Image to Bitmap
Upload your image as binary(byte array)
here is code you can reffer :
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"Your_file");
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
}
catch (Exception e)
{
// show error
}

HttpGet in Android/Java with GZip encoding

I am running MVC 4 on my server and to save a bit of data for my users I figured I would enable GZip encoding, to do this I simply used:
(C#)
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
In my android application I use:
(Java)
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
When I use GZip the Java code nuts out and causes GC to run, I was never patient enough to wait for it to return.
When I took off GZip from the server it ran perfectly fine. The function to get the response returns straight away with no problem.
I tried adding this to the java code:
httpGet.addHeader("Accept-Encoding", "gzip");
With no success.
Question is, is there something I'm not getting? Can I not put the response in a stream if it is using GZip? Am I meant to use the stream and uncompress it after?
What am I doing wrong?
Instead of using
DefaultHttpClient client = new DefaultHttpClient();
you can use
ContentEncodingHttpClient client = new ContentEncodingHttpClient();
which is a subclass of DefaultHttpClient and supports GZIP content.
You need Apache HttpClient 4.1 for this.
If you have Apache HttpClient 4.2, you should use
DecompressingHttpClient client = new DecompressingHttpClient();
if you have Apache HttpClient 4.3, you should use the HttpClientBuilder

Getting a compressed version of web page

I am using HttpClient 4.1 to download a web page. I would like to get a compressed version:
HttpGet request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse response = httpClient.execute(request,localContext);
HttpEntity entity = response.getEntity();
response.getFirstHeader("Content-Encoding") shows "Content-Encoding: gzip"
however, entity.getContentEncoding() is null.
If I put:
entity = new GzipDecompressingEntity(entity);
I get:
java.io.IOException: Not in GZIP format
It looks like the resulting page is plain text and not compressed even though "Content-Encoding" header shows it's gzipped.
I have tried this on several URLs (from different websites) but get the same results.
How can I get a compressed version of a web page?
Don't use HttpClient if you don't want your API to handle mundane things like unzipping.
You can use the basic URLConnection class to fetch the compressed stream, as demonstrated by the following code :
public static void main(String[] args) {
try {
URL url = new URL("http://code.jquery.com/jquery-latest.js");
URLConnection con = url.openConnection();
// comment next line if you want to have something readable in your console
con.addRequestProperty("Accept-Encoding", "gzip,deflate");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String l;
while ((l=in.readLine())!=null) {
System.out.println(l);
}
} catch (Exception e) {
e.printStackTrace();
}
}

java : upload files to HTTP server using POST, server code issue?

I am new to java and I have to transfer file from Android application to server. I took help from the link
Uploading files to HTTP server using POST. Android SDK
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Its PHP code and works perfectly fine but I have to implement the server side code in Java not in PHP.
I googled and find the code from link enter link description here
InputStream in = request.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
String s = buf.toString();
I am new to java so donot know how to write this code. I have NetBeans netbeans-7.1.1-ml-javaee installed.
Can somebody tell me that if this code is correct and how to put it in file or which type of file. I have created project but do not know how to put this code in file.
Edits:
Andriod code is working fine ... I want to develop Server code to get and save file
i hope this code can help u
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Image_url);
MultipartEntity mpEntity = new MultipartEntity();
File file = new File(selectedImagePath);
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("photo", cbFile);
mpEntity.addPart("user_id", new StringBody(SmallyTaxiTabbar.unique_ID));
mpEntity.addPart("password", new StringBody(SmallyTaxiTabbar.password));
post.setEntity(mpEntity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("PICTUREServer Response", Response);
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
alert=(jsonobject.getString("alert"));
client.getConnectionManager().shutdown();
}
catch (Exception e) {
Log.e("TAGPost", e.toString());
}
where SmallyTaxiTabbar.unique_ID, password is parameter value
*i Hope this code can help u ! *
check if this library helps you. I have created wrappers for several http methods..
https://github.com/nareshsvs/android-libraries
The Apache Commons FileUpload library should help you process the content of the POST request in Java from a server point of view. It can be integrated with Servlets if required.
In particular, it will process the multipart/form-data content for you (which you would otherwise have to do manually if you were reading the request's InputStream directly line by line).

Categories