Android HTTP POST request to server (need explanation) - java

URL url = new URL("url");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);// i can delete this nothing happens
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(valueIWantToSend);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
This code above post my value: valueIWantToSend to my server. Everything is working fine, but i want to ask: Why then i remove this line:
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
Nothing is shown on my server, but then i add this line everything is working great, but why ? I am not using Reader in this connection so what i miss understood?

I think u should call urlConnection.connect()
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();

Related

HTTPURLConnection write command works only with read

I am writing a file into AWS S3 bucket using HTTPURLConnection. This connection's outputstream-write command works only if it is followed by getInputStream or getResponseCode. Please help me to understand this. Is it required to read responseCode?
URL endpointUrl = new URL("muURL");
HttpURLConnection connection = (HttpURLConnection) endpointUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Authorization", authorization);
connection.setRequestProperty("x-amz-content-sha256", hashPayload);
connection.setRequestProperty("X-Amz-Date", myDate);
connection.setRequestProperty("Content-Type","application/octet-stream");
connection.setRequestProperty("Content-Length",contentLen);
//connection.setRequestProperty("Accept","*/*");
connection.setUseCaches(false);
//connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
StringBuilder builder = new StringBuilder();
// If I comment this line which gets responseCode , then file is not written in S3.
builder.append(connection.getResponseCode());
wr.flush();
wr.close();
connection.disconnect();
I am expecting this code to work without getResponseCode line.

Java Post Data HttpsUrlConnection or HttpClient 4.5

I am trying to do what I thought was a simple task. I need to POST data to a PHP server. I have tried this solution but in Apache HttpClient 4.5 I can't find BasicNameValuePair in the package. Upon further research I thought I'd try StringEntity...nope not in 4.5 either (that I can find at least). So I tried to do it with HttpsURLConnection. The problem with that is I can't figure out how to add a name to my parameter and with a name, I don't know how to access in PHP with $_POST['name'].
My Current Code:
String json = gson.toJson(data);
URL url = new URL("https://www.domain.com/test.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(json.length()));
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
Try to use DataOutputStream and flush it afterward.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeChars(json);
wr.flush();
wr.close();

Won't send all parameters to post http request

I am trying to send a http request with java. This is my code:
String AnnonseUrl = "http://webpage.no/insert_annonse.php?info="+info+"&tittel="+tittel+"&bedriftsNavn="+bedriftsNavn+"&kontaktEmail="+kontaktEmail+"&varighet="+varighet+"&frist="+frist+"&url="+url+"&sted="+sted+"&kontaktNavn="+kontaktNavn;
URL url = new URL(AnnonseUrl);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
uc.getInputStream()));
in.close();
Only the first three parameters are submitted..
If I copie the string "AnnonseUrl" and paste it in to my browser, then everything works fine.
When doing a post the parameters are send in the Http Body:
Try this:
URL u = new URL("http://www.stackoverflow.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
Where urlParameters is something like:
String urlParameters =
"tittel="+URLEncoder.encode(tittel,"UTF-8")
+"&bedriftsNavn"+URLEncoder.encode(bedriftsNavn,"UTF-8");

set methods aren't working for HttpsURLConnection

I'm trying to make a rest request in java. I tested the web service using RestClient in Firefox and it works great.
When i try to modify the HttpsUrlConnection instance in java the values aren't changing and i get a 500 response code.
Here's my code:
public String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;
}
I'm stucked at this point and cannot find anything to make this work.
Thank you!
I actually think it's a bug with HttpsURLConnection. As i changed it to a HttpURLConnection object everything works just fine.

Java Http POST with basic authorization and redirect

The program does a http post with basic authorization just fine but when the post is complete the page is redirected to a success page. The redirect failes due to 401 authorization failed.
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "basic " +base64);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
The line
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
fails due to 401 authorization failed...
I have also tried adding
conn.setRequestProperty("Authorization", "basic " +base64);
after
wr.flush();
I get the error of "Already connected". Evidently the authorization that I set doesn't follow over to the redirect. Any solutions to this problem is greatly appreciated.
You have 2 options you can try:
Use the setDefaultRequestProperty (see http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setDefaultRequestProperty%28java.lang.String,%20java.lang.String%29) method to set the Authorization header.
Disable automatic redirect following: http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects%28boolean%29 and do it manually.
Here is the working solution for anyone else who has this problem. Thanks again to Femi for providing a workaround idea.
URL url = new URL(page);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "basic " +base64);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){
url = new URL(conn.getHeaderField("Location"));
conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Authorization", "basic " +base64);
}
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

Categories