How to set content-length in android? - java

I want to get content size by request.getContentLength() in server client JSP page.
But request.getContentLength() always return -1, i do not why?
Android snippet code:
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//conn.setChunkedStreamingMode(100);
conn.setConnectTimeout(setTimeOut>0?setTimeOut:timeoutConnection);
conn.setReadTimeout(setTimeOut>0?setTimeOut:timeoutConnection);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");
//conn.setRequestProperty("content-length", "10");
//conn.addRequestProperty("content-length", "20");
conn.setFixedLengthStreamingMode(30);
conn.setRequestProperty("Charsert", ENCODING);
conn.setRequestProperty("Content-Type", "multipart/form-data"
+ ";boundary=" + java.util.UUID.randomUUID().toString());
conn.connect();

You are using conn.setChunkedStreamingMode(100) that will effectively enable the chunked transfer encoding in chunks of 100 bytes when the content-lenght is unknown in advance.
Use conn.setFixedLengthStreamingMode(int len) if you know in advance the length of the content you are going to send in the body of the request.

Related

Why does a number appear between the headers and the body in a HttpURLConnection request?

I would like to send a multipart request. Unfortunately the request fails, because the HttpURLConnection library inserts a number between the headers and the content, like this:
POST / HTTP/1.1
Connection: Keep-Alive
Content-Type: multipart/form-data;boundary=*****
Transfer-Encoding: chunked
User-Agent: Dalvik/2.1.0 (Linux; U; Android 9; SM-G970F Build/PPR1.180610.011)
Host: localhost:7777
Accept-Encoding: gzip
115
test
Why is that number (115) there? How is it possible to avoid that?
This is my simplified code:
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("http://localhost:7777");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(1024);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(conn.getOutputStream()));
dos.writeBytes("test");
fileInputStream.close();
dos.flush();
dos.close();

POST request working fine with POSTMAN/Advance rest client while giving 400 error with HttpUrlConnection

I am a newbie to HttpClient so not sure what's wrong I am doing. I am hitting one POST request through HttpUrlConnection. After sending the request when I check the logs it doesn't hit the entire request. My URL is https://www.example.com/product/pd/v1/gql when I check on the server, for URI, it shows v1/gql and give 400 error. while the same request works perfectly from Postman and advance rest client.
URL obj = new URL("https://www.example.com/product/pd/v1/gql/");
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Cookie", "_bb_vid=djfhhf");
JSONObject val = new JSONObject(gqlValue2);
JSONObject jObj = new JSONObject();
jObj.put(gqlKey1, gqlValue1);
jObj.put(gqlKey2, val);
System.out.println(jObj);
OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write(jObj.toString());
wr.flush();

Send sentence using setRequestProperty

I am sending image and some text from my Android app to PHP server and I am using this code to do it:
...
URL url = new URL("http://example.com/upload.php");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
httpURLConnection.setRequestProperty("File", imagePath);
httpURLConnection.setRequestProperty ("Text", someText);
...
This works when someText variable is a word, but when it's a sentence with spaces between words it doesn't work.
Why is that? And is there a way to make it work?

How to send post parameter which can be read by php

I have some connection to url:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
How I can send post parameter to this url that php function: http://www.php.net/manual/en/reserved.variables.request.php can read it ? I try to according this question: Java - sending HTTP parameters via POST method easily but with no success. It just display empty array
php code:
print_r($_REQUEST,1)
java code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("category_name", categoryName);
connection.setRequestProperty("complete", complete);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
connection.getResponseCode();
wr.flush();
wr.close();
connection.disconnect();
You forgot to set the Content-Type header, and you need to write the category_name and complete values as a string to the stream.
Quoting the code from the post you mentioned:
String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
As you can see, he sets the headers (Content-Type, Charset and Content-Length) and then writes the POST data to the stream.
The POST data is just like the GET format: key-value pairs seperated by &, and the key and value are seperated by =.
As the Content-Type is set to www-form-urlencoded, you need to 'url encode' the key and value values. You can do this using the URLEncoder.encode method.
The urlParameters for your POST data would be:
String urlParameters = "category_name=" + URLEncoder.encode(categoryName) + "&complete=" + URLEncoder.encode(complete);

Java - Read cookie after a post

I'm having trouble reading what cookies are being sent when making a POST in java.
Here's my code:
public static void main(String[] args) throws MalformedURLException, IOException {
String urlParameters = "votebut=";
String request = "http://www.runelocus.com/toplist/vote-17648.html";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
for (String cookie : cookies) {
System.out.println("Cookies: " + cookie);
}
connection.disconnect();
}
This is what it prints:
Cookies: PHPSESSID=48863f8c3adcbddf0e77e7f1b450fc0e; path=/
This is what I want it to print:
ki_u=68debd85-c1af-f1ff-2e6c-4146755c6e26; ki_t=1354418220596%3B1354418220596%3B1354422379616%3B1%3B36;
Any help please?
Thanks
It is not possible to read that cookies in that way.
In response to http://www.rune...17648.html you only get PHPSESSID cookie in response headers.
That cookies which you are looking for (ki_u and ki_t) are set by JavaScript code in this file:
http://s3.amazonaws.com/ki.js/45645/919.js
So to actually get that cookies values you need to replicate browser behavior or actually use a browser (to request the html page, parse it, download referred resources (particularly 919.js) and execute JavaScript code).

Categories