EDIT: this is what is shown in my website logs
xx.xx.xxx.xx - - [27/Jan/2012:17:42:24 -0500] "POST /dir/addData2.php HTTP/1.1" 200 - www.mywebsites.com "-" "Java/1.7.0" "-"
I am hosting my website at 1&1, and I want to have page blank.php that should take a POST request and upload it to my database. I think I am sending my POST properly, and that somehow I am not handling it properly on my website. Because nothing is being inserted to my database. The response has content length 0, but even if i send a header with the length of the string it wont change. Another option is that the host wont allow me to do remote post requests (still waiting on reply).
I send the post request from a Java application like this:
URL url = new URL("www.mywebsite.com/blank.php");
HttpURLConnection request = (HttpURLConnection)url.openConnection();
request.setRequestProperty("Content-type","application/x-www-form-urlencoded");
request.setRequestMethod("POST");
OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
String data = URLEncoder.encode("account", "UTF-8") + "=" + URLEncoder.encode(message[0], "UTF-8");
data += "&" + URLEncoder.encode("message", "UTF-8") + "=" + URLEncoder.encode(message[2], "UTF-8");
data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(message[0], "UTF-8");
post.write(data);
post.flush();
/*
/ String example
/account=103&message=Feller+1391.88+0&type=103
*/
The response from the server is:
null=[HTTP/1.1 200 OK]
Date=[Fri, 27 Jan 2012 21:59:10 GMT]
Content-Length=[0]
Keep-Alive=[timeout=2, max=200]
Connection=[Keep-Alive]
Content-Type=[text/html]
Server=[Apache]
X-Powered-By=[PHP/5.2.17]
My webpage has this basic PHP code (right now, will improve/check for stuff later)
$link = mysql_connect($hostname, $username, $password);
$db_selected = mysql_select_db($database, $link);
$query = "INSERT INTO newData(account, message, type) VALUES('$_POST[account]', '$_POST[message]', '$_POST[type]')";
mysql_query($query) || die();
I want to point out that I do not have a private server, and I will probably use http://hc.apache.org/httpcomponents-core-ga/examples.html later. Right now I just want to send a string from my Java application, receive it with PHP and insert to MySQL database.
Yes, I'm certain your ISP allows both "post" and "get" HTTP server requests.
Superficially, both your Java and PHP look "OK".
STRONG SUGGESTION:
1) Check your Apache logs on the server.
Make sure the request arrived (it probably did).
Check for errors (there could well be none for your request - but you SHOULD see SOMETHING in the Apache error log.
2) Verify PHP is working.
Writing a "hello world" page with "phpinfo ();" is a good way to do this.
3) Verify that MySQL is working.
Writing a "hello world" PHP page to verify you can 1) connect, 2) make a query, and 3) echo the query back in your web browser is ideal.
4) Verify that you can successfully read the "$_POST[account]" value you THINK you're getting from the client.
5) At that point, you should be able to:
a) have the client communicate with your server
b) read the post request and write it to your database
'Hope that helps .. and please post back with any specific questions/problems you might have.
You haven't told the client code that this is a POST request. It will probably do a GET by default.
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
It looks like you're not setting the request method on your HttpUrlConnection, and the default is GET. You'd need something like
request.setRequestMethod("POST");
If that doesn't work, I'd consider rather using the Apache HTTP client right away from the beginning, it's easiert to use than Java's standard HTTP client API.
Related
I want to create QualityGates with the Web API in java.
String auth = username + ":" + password;
String authEncoded = Base64.getEncoder().encodeToString(auth.getBytes());
URL sonar = new URL("http://xxx.xxx.xxx.xx:9000/api/qualitygates/create");
HttpURLConnection conn = (HttpURLConnection) sonar.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authEncoded);
I dont seem to find anything in the topic of POST to web API.
In the Code i basically try to connect to the API with the Admin user authentication.
The Problem is, it doesnt matter what i do i always get ResponseCode 400. I know that it needs a name as a Property to create the QualityGate but that also doesnt seem to work.
My Question:
What do i need to do to use the POST method on web API's.
Best regards!
This isn't really a SonarQube question. It's a question about how to use POST apis. The API is returning a 400 error because you're not sending any data in the POST, and a POST expects data.
Read the answer to the following thread for hints on how to send data in a POST: Java - sending HTTP parameters via POST method easily .
I am trying to complete the Instagram Oauth flow,
I currently have the authorization code which I'm to exchange for the access token. I am to make an x-www-form-urlencoded POST request to this endpoint
"https://api.instagram.com/oauth/access_token?"
This is what I've done so far.
String query = "https://api.instagram.com/oauth/access_token/?client_id=" + clientId +"&client_secret="+ clientSecret+ "&grant_type=authorization_code&redirect_uri="+ redirectUri + "&code=" + code
String response = new URL(query).getText()
A JSON string is expected as response.
Please Keep in mind that I'm a beginner.
I haven't read the Instagram documentation but based on your example code there's a couple of things to keep in mind:
you mentioned that you have to make a POST request, your example makes a GET request
never build a URL with untrusted parameter values. This basically means: always encode parameters, never trust them.
There are dozens of 3rd party HTTP Request libraries that give you flexibility and easier insight into aspects like timeouts and redirects. Java 11 has a built-in HTTP client that might ease this as well. But building on your code provided in your question using basic Java connection primitives this might work:
URL url = new URL("https://api.instagram.com/oauth/access_token/?client_id=${URLEncoder.encode(clientId, 'UTF-8')}&client_secret=${URLEncoder.encode(clientSecret, 'UTF-8')}&grant_type=authorization_code&redirect_uri=${URLEncoder.encode(redirectUri, 'UTF-8')}&code=${URLEncoder.encode(code, 'UTF-8')}")
def jsonString = ((HttpURLConnection) url.openConnection()).with {
setRequestMethod('POST')
setRequestProperty('Accept', 'application/json')
setDoInput(true)
connect()
if (getResponseCode() >= 400)
throw new Exception("Error code = ${getResponseCode()}")
inputStream.text
}
Every URL parameter is encoded so that any non-URL safe characters they contain are made safe, then we tell the connection that it will be a 'POST' and that we expect to get back json as input. inputStream.text is groovy code that takes an inputstream from the connection and reads all of the contents and then closes the stream. Since it is the last line of the with closure it is automatically returned as the value of the closure and assigned to the variable jsonString.
Hy,
I want to do calls to a different rest api from my play application. I'm using the javaws included library.
The specific call requires that I send form data. However I have no idea how I can send the correct data along with my request.
As far as I can see the library only supports sending url-encoded-form-data.
Does anyone know how I can send form-data along with my request like a normal website doing a form submission?
At the moment I have this:
Promise<WSResponse> promise = WS.url("http://localhost:"+port+"/login").setContentType("multipart/form-data").post("emailAddress=" + email +"&password=" + password);
Thanks,
Use application/x-www-form-urlencoded instead of multipart/form-data.
Promise<WSResponse> promise = WS.url("http://localhost:"+port+"/login")
.setContentType("application/x-www-form-urlencoded")
.post("emailAddress=" + email +"&password=" + password);
I am currently working on a simple java program that tests ping, upload speed, and download speed. It is for a class project, and therefore rather than using java's httpURLConnection package, I'm doing it manually using Java Sockets. I found it quite easy to find the format of a GET request, put cannot find the format of a PUT.
Here, for example, is how my GET request looks:
//Create GET request
outToServer.writeBytes("GET / HTTP/1.1\r\n
+ "Host: " + server + "\r\n"
+ "Connection: close\r\n\r\n");
where outToServer is a DataOutputStream using the outputStream of a Socket. I am looking for a similar way to perform a PUT to upload a file to a server and measure the time.
Thank you very much for any help!
In short, format is the same, it has "PUT" instead of "GET" and it is usually used to "add" or "update" entities in the server, so after the header you would get an empty line (\r\n\r\n) and then a body, whose content type would correspond to the header "content-type" (like, say, text/html or application/json) An example of what a PUT request would look like:
PUT /boo/foo.txt HTTP/1.1
Host: www.foo.com
Content-Type: plain/text
This is a testing content for the text file foo.txt
Now, the server must support the method PUT (it is not required for a server to support such method)
Recently it appears that resumable upload is not working. All my requests for upload are returning 500.
Here is the exception stacktrace I receive:
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3A0B6Qc9CKRbiEMNTQ2NWYzMjEtY2EwNC00NzRhLWFjNGQtNGEzNzEzNzc4MTRj/contents/?convert=false&upload_id=AEnB2UpuikBd2Rd1wk1j8BPAI3KKTJ1pWoAJEPm3KZCBqLIqj6Rm9uOy7NezC8dzROUghRpTI6Clblj8j4zhKO91ductHL2LBA
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)
at GoogleDocsManager.uploadWithResumableUpload(GoogleDocsManager.java:1342)
This is the code (no changes were made since yesterday (21-11-2012))
String link = initiateSession(mediaBytes, contentType, title, withConvert);
URL url = new URL(link);
HttpURLConnection copyHttpUrlConn = (HttpURLConnection) url.openConnection();
copyHttpUrlConn.setDoOutput(true);
copyHttpUrlConn.setRequestMethod("PUT");
copyHttpUrlConn.setRequestProperty("Content-Type",contentType);
copyHttpUrlConn.setRequestProperty("Content-Length", mediaBytes.length + "");
String range = "bytes 0-" + (mediaBytes.length - 1) + "/" + (mediaBytes.length);
copyHttpUrlConn.setRequestProperty("Content-Range", range);
OutputStream outputStream = copyHttpUrlConn.getOutputStream();
outputStream.write(mediaBytes);
System.out.println("Code: " + copyHttpUrlConn.getResponseCode());// here I receive the exception
Now I really don't know where to write this kind of posts... From the old DocumentList Api group I was redirected here.
I hope that this issue is fixed soon (I have 2 different programs which use this resumable upload and yesterday both were ok, so I guess that this problem is not on my side)
Best regards,
500 errors in the Drive SDK are a way of life. I get them around 0.5% of the time. Try wrapping your API calls in an exponential backoff and retry.
Because your error is on an upload, you might want to verify that the file you're uploading has valid contents according to its mime type. (eg. if it's text/html, does the file contain valid html).
After 4 days the errors stopped (with no changes made to the code).
PS: For a period there were a strange behaviour (on google appengine not working, and localhost yes).