I have an applicaction that makes a post request inserting a user like this:
email=Ali#gmail.com&name=Alí
But then hits the server with a wired caracter
...
body: {
email: Ali#gmail.com,
name: Al?
}
And is like this how is save in the database.
My code in the server is simple
router.post('user', (req, res) => {
const newUser = new User({
email: req.body.email,
name: req.body.name
});
newUser.save().then((usr) => {
const resp = { user: usr.fields(), code: 200 };
return res.status(200).send(resp);
}).catch(err => {
console.log(err);
});
});
The client is using HTTPConnection in Java:
StringBuffer response = new StringBuffer();
HttpURLConnection con = null;
URL obj = new URL(url);
obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(3306);
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("charset", "utf-8");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
if (params != null) {
wr.writeBytes(params);
}
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I think you should escape the "í" character in your url request (client side).
Something like
email=Ali#gmail.com&name=Al%ED%20%0A
Related
Can someone explain me how to pass JSON parameter in request body.
I am using HttpURLConnection to create the connection, as below:
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");
JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
How can I put set the req body here?
For specifying the body of your request:
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()
Hello guys I am trying to send get request in java with header. I am looking for a method like conn.addHeader("key","value); but I cannot find it. I tried "setRequestProperty" method but it doest not work..
public void sendGetRequest(String token) throws MalformedURLException, IOException {
// Make a URL to the web page
URL url = new URL("http://api.somewebsite.com/api/channels/playback/HLS");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Authorization", "bearer " + token);
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
It returns Httpresponse 401 error.
My office mate use unity c# to send get request header his codes looks like the fallowing.
JsonData jsonvale = JsonMapper.ToObject(reqDataGet);
// Debug.Log(jsonvale["access_token"].ToString());
// /*
string url = "http://api.somewebsite.com/api/channels/playback/HLS";
var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) =>
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
}
break;
}
});
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "bearer " + jsonvale["access_token"].ToString());
request.Send();
Any help?
In Java I think you want something like this.
String url = "http://www.google.com/search?q=stackoverflow";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "My Example" );
int responseCode = con.getResponseCode();
I have a code that handle the post and get request . but it should response when the post request come . I dont want to use servlet because it need the tomcat or jetty and its become more complex .
how I should know post request recived ?
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
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 = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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();
//print result
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception {
while (true) {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
}
Problem Description
I'm trying to write a code which is sending POST request to the server. As server yet doesn't exist I can't test this part of code. With the request I must send XML as a String which look likes the string below:
String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"
Solution
String url = "https://testurl.com/somerequest";
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 = String.format("request=%s", XMLSRequest);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Question
Is this right way to send String (XML like string) as POST request to the server?
To POST a SOAP request, you would want to write the xml to the body of the request. You do not want to write it as a parameter of the request.
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream(); //get output Stream from con
os.write( XMLSRequest.getBytes("utf-8") );
os.close();
Specially this code works well for sending XML string in SOAP calling
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public static String sendXmlString(String xmlString){
String xmlResponceString = "";
try {
// Replace here with your target URL
URL url = new URL("http://www.dneonline.com/calculator.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set timeout as per needs
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
// Set DoOutput to true if you want to use URLConnection for output.
// Default is false
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestMethod("POST");
// Set Headers
connection.setRequestProperty("Accept", "*/xml");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("User-Agent", "");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Write XML
OutputStream outputStream = connection.getOutputStream();
byte[] b = xmlString.getBytes("UTF-8");
outputStream.write(b);
outputStream.flush();
outputStream.close();
// Read XML
InputStream inputStream = connection.getInputStream();
byte[] res = new byte[2048];
int i = 0;
StringBuilder response = new StringBuilder();
while ((i = inputStream.read(res)) != -1) {
response.append(new String(res, 0, i));
}
inputStream.close();
xmlResponceString = new String(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
return xmlResponceString;
}
I'm try to send Post request to Google elevation API and expecting response
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
private final String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true&key=<API KEY>";
URL obj = new URL(ELEVATION_API_URL);
java.net.HttpURLConnection con = (java.net.HttpURLConnection)obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I'm sending request in this manner but I'm getting response code as 400.This is working when request sent from browser. What is wrong with this code.
To Allow me to get XML back I made the following changes to your project
StringBuilder response = new StringBuilder(); // placed on the top of your Class
**wr.writeBytes(urlParameters.toString());** // as you have it in your code
System.out.println("ResponseMessage : " + connection.getResponseMessage());
System.out.println("RequestMethod : " + connection.getRequestMethod());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
wr.flush();
wr.close();
// I changed the URL to :
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/xml";
//**I get XML in the response**
return response.toString();
I think there is a problem with the url parameters.
Firstly because sending an empty elevation api request does return a code 400 (Invalid request. Missing the 'path' or 'locations' parameter.).
Secondly because this works (returning 200) :
public void test() throws Exception {
String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true";
URL obj = new URL(ELEVATION_API_URL + "?" + urlParameters);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
//String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
}