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");
Related
When I parse an JSON object, it gets parsed easily and in the correct format. But as soon as I send the same thing to the server side, values go missing.
JSONArray check0 = new JSONArray();
JSONArray check1 = new JSONArray();
JSONArray check2 = new JSONArray();
check0.put(v11);
check0.put(v12);
check0.put(v13);
check1.put(c11);
check1.put(c12);
check1.put(c13);
check4.put(t11);
check4.put(t12);
check4.put(t13);
draft.put("check2",id11);
draft.put("check3",t11);
draft.put("check0",check0);
draft.put("check1",check1);
draft.put("check4",check4);
where v11,v12.......t12,t13 are string variables.
My code for sending data:
URL url = new URL("http://10.0.2.2:8080/initial");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new
DataOutputStream(connection.getOutputStream());
System.out.println(draft.toString());
dStream.writeBytes(draft.toString());
System.out:
{"Check1":["5","4","4"],"Check0":["6","44","4"],"Check2":"17082017123406","Check4":"1228123682","Check3":["4","4","4"]}
Code to receive the post request:
app.post('/initial', function(req, res){
console.log("POST received: "+ JSON.stringify(req.body));
res.end("cool");
});
Console output
POST received:
{"{\"Check1\":":{"\"5\",\"4\",\"4\"":{"\"6\",\"44\",\"4\"":{"\"4\",\"4\",\"4\"":""}}}}
try using the following
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Example
private JSONObject uploadToServer() throws IOException, JSONException {
String query = "https://example.com";
String json = "{\"key\":1}";
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(result);
in.close();
conn.disconnect();
return jsonObject;
}
I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.
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();
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();
I've got a webserver setup ready to receive images and I'd like to have a client in Java send the image along with two POST arguments, upon searching the web I only found ways to do this with Apache's API but I'd prefer to do this in vanilla Java.
Any help will be appreciated.
Something along the lines of...
String url = "https://asite.com";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "aparam=1&anotherparam=2";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
You can add more headers, and add more to the output stream as required.