I have a server and a client,
on the server side i have this handler
#Override
public void handleHttpRequest(HttpRequest httpRequest,
HttpResponse httpResponse,
HttpControl httpControl) throws Exception {
// ..
}
The question is how to send data from the client side and what method in the server side will contain the data sent?
If there is a better way to perform the communication using webbit, it will be welcomed too.
In a POST request, the parameters are sent as a body of the request, after the headers.
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
This code should get you started:
String urlParameters = "param1=a¶m2=b¶m3=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();
Alternatively you could use this helper to send POST the request and get the request
public static String getStringContent(String uri, String postData,
HashMap<String, String> headers) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(uri));
request.setEntity(new StringEntity(postData));
for(Entry<String, String> s : headers.entrySet())
{
request.setHeader(s.getKey(), s.getValue());
}
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
}
Usually one will extend HttpServlet and override doGet.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html
I am not familiar with webbit but I do not think it is a Servlet webserver. It mentions that it serves static pages.
Related
I am calling Traccar API from my AsyncTask class. I need to pass JSON and Basic Authentication using POST method. I have this inside my doInBackground but it returns 400 Bad Request. I cannot pinpoint what's wrong. I'm pretty sure URL and credentials are all correct.
String credentials= "my_username:my_password";
String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");
URL url = new URL("https://server.traccar.org/api/devices");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization", credBase64);
if (this.postData!=null)
{
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(this.postData.toString());
writer.flush();
}
int statusCode = urlConnection.getResponseCode();
if(statusCode == 200)
{
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = inputStream.toString();
}
else
{
Log.e(TAG, "Error" + statusCode);
}
I am trying to do a java rest web service using "POST" method.My client part to invoke the web service is working proper.But i am facing difficulty in accessing the passed parameters by "POST" method.Any help would be appreciable. Here is my client side
public static void main(String[] args) throws IOException
{
String urlParameters = "param1=world¶m2=abc";
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}
And here is my java rest web service
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public String getpostdata(#QueryParam("param1") String param1,#QueryParam("param2") String param2)
{
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",param1);
return jObjDevice.toJSONString();
}
The parameter param1=world.But when i run the web service,I am getting json string as {"Hello":null} instead of {"Hello":"world"}.Please suggest for any changes.I think the problem is with annotation i.e #QueryParam.If this is the case,then please provide proper way to access the parameter using proper annotation.
How in java, can I send a request with x-www-form-urlencoded header. I don't understand how to send a body with a key-value, like in the above screenshot.
I have tried this code:
String urlParameters =
cafedra_name+ data_to_send;
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
But in the response, I don't receive the correct data.
As you set application/x-www-form-urlencoded as content type so data sent must be like this format.
String urlParameters = "param1=data1¶m2=data2¶m3=data3";
Sending part now is quite straightforward.
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}
Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded.
private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
For HttpEntity, the below answer works
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "first.last#example.com");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
For reference:
How to POST form data with Spring RestTemplate?
Use Java 11 HttpClient
The HTTP Client was added in Java 11. It can be used to request HTTP resources over the network. It supports HTTP/1.1 and HTTP/2, both synchronous and asynchronous programming models, handles request and response bodies as reactive-streams, and follows the familiar builder pattern.
https://openjdk.java.net/groups/net/httpclient/intro.html
HttpClient client = HttpClient.newHttpClient();;
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(targetUrl))
.POST(urlParameters)
.headers("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Problem with the Response!
I had a similar issue when I was sending the request of media type application/x-www-form-urlencoded from Postman I was receiving a correct response.
However, when sending the request using code, I was receiving jargon somewhat like:
�-�YO�`:ur���g�
.n��l���u)�i�h3J%Gl�?����k
What I tried:
Out of frustration for multiple days tried all the possible solutions from changing character sets to changing header values to code changes and whatnot.
Solution lies in Postman.
Select Java-OkHttp
Copy the code and paste it into IDE.
That's it.
Reference for HttpOk:
https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Building off of Navoneel's answer, I like to use StreamEx's EntryStream.
Here is Naveoneel's method re-written.
private String getDataString(HashMap<String, String> params)
{
return EntryStream.
of(data).
mapKeys(key -> URLEncoder.encode(key, StandardCharsets.UTF_8)). // Encode the keys
mapValues(value -> URLEncoder.encode(value, StandardCharsets.UTF_8)). // Encode the values
join("="). // Create a key=value
joining("&"); // Assemble into key1=value1&key2=value2...
}
I am trying to write a simple HTTP server in Java that can handle POST requests. While my server successfully receives the GET, it crashes on the POST.
Here is the server
public class RequestHandler {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "hello world";
t.sendResponseHeaders(200, response.length());
System.out.println(response);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
And here is the Java code I use to send the POST
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://localhost:8080/requests";
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());
}
Each time the POST request crashes on this line
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
but when I change the URL to the one provided in the example where I found this it works.
Instead of
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Use
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
You are connecting to a URL which is not HTTPS. When you call obj.openConnection(), it decides whether the connection is HTTP or HTTPS, and returns the appropriate object. When it's http, it won't return an HttpsURLConnection, so you cannot convert to it.
However, since HttpsURLconnection extends HttpURLConnection, using HttpURLConnection will work for both http and https URLs. The methods that you are calling in your code all exist int the HttpURLConnection class.
I need to post data to server using HttpURLConnection. Data contains Thai character as well. Server which accept post request accept encoding UTF-8 and TIS-620 both. When I directly post data from rest client it works fine, but when I send same request from java code it is not working properly, I mean when I send UTF-8 format data it gives parse exception and when I use TIS-620 instead thai text in server I am getting some speial character square etc.( I do not any have handle on server which accept data )
I am setting same header property for HttpURLConnection which I set for rest client in browser.Please let me know what could be going wrong here
As per my requirement I have to write this code in servlet , and servlet is called from browser AJAX call. In JQUERY AJAX call while sending data I am setting
beforeSend: function(xhr) {
xhr.setRequestHeader( "Content-type", "application/json; charset=UTF-8" );
},
I changed UTF-8 to TIS-620 All places but no luck
Some finding :
when I set
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
and Print connection.getContentType() it is only printing application/json
If I send only English text it works fine. I am giving servlet code below which accept post request and POST it to server
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.err.println("************** POST CALLED **************");
//PRINT SERVLET REQUEST PROPERTY
System.err.println("CharacterEncoding : "+ request.getCharacterEncoding());
System.err.println("ContentType : "+request.getContentType());
//SEND GET REQUEST AND FETCH XCSRF TOKEN
String dummyServiceUrl = "GET_LOT_SRV/get_lot";
String xcsrfToken = null;
HttpURLConnection connection = null;
String requestURL = httpPrefix + hostName + semiColon + portNumber + forwardSlash + dummyServiceUrl;
List<String> cookies = null;
try {
URL gatewayServiceUrl = new URL(requestURL);
connection = (HttpURLConnection) gatewayServiceUrl.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", this.getBasicAuth());
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("x-csrf-token", "fetch");
connection.connect();
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
//ON SUCCESS GET XCSRF TOKEN AND IN SAME SESSION POST DATA
requestURL = httpPrefix + hostName + semiColon + portNumber + forwardSlash + request.getQueryString();
gatewayServiceUrl = new URL(requestURL);
connection = (HttpURLConnection) gatewayServiceUrl.openConnection();
//SET CONNECTION PROPERTY
connection.setRequestMethod("POST");
xcsrfToken = connection.getHeaderField("x-csrf-token");
cookies = connection.getHeaderFields().get("set-cookie");
// SET COOKIES
for (String cookie : cookies) {
String tmp = cookie.split(";", 2)[0];
connection.addRequestProperty("Cookie", tmp);
}
//SET HEADERS
connection.setRequestProperty("Authorization", this.getBasicAuth());
connection.setRequestProperty("x-csrf-token", xcsrfToken);
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("DataServiceVersion", "2.0");
connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//SET USERS INPUT DATA TO OUTPUT STREAM
String payload = this.getDataFromStreamPost(request.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(payload.getBytes());
dataOutputStream.flush();
dataOutputStream.close();
//POST DATA AND CHECK RESPONSE
connection.connect();
response.setStatus(HttpURLConnection.HTTP_CREATED);
response.setContentType("application/json; charset=TIS-620");
response.getWriter().println(this.getDataFromStream(connection.getInputStream()));
} else {
System.err.println("XCSRF GET FAILURE "+connection.getResponseCode());
response.setStatus(connection.getResponseCode());
response.setContentType("application/json; charset=TIS-620");
response.getWriter().println(this.getDataFromStream(connection.getInputStream()));
}
} catch (Exception e) {
System.err.println("EXCEPTION OCCURED IN POST : "+e.getMessage());
response.setStatus(connection.getResponseCode());
response.setContentType("application/json; charset=TIS-620");
response.getWriter().println(this.getDataFromStream(connection.getErrorStream()));
}
}
private String getBasicAuth() {
String userpass = userName + ":" + password;
return "Basic "
+ javax.xml.bind.DatatypeConverter.printBase64Binary(userpass
.getBytes());
}
private String getDataFromStream(InputStream stream) throws IOException {
StringBuffer dataBuffer = new StringBuffer();
BufferedReader inStream = new BufferedReader(new InputStreamReader(
stream));
String data = "";
while ((data = inStream.readLine()) != null) {
dataBuffer.append(data);
}
inStream.close();
return dataBuffer.toString();
}
private String getDataFromStreamPost(InputStream stream) throws IOException {
StringBuffer dataBuffer = new StringBuffer();
BufferedReader inStream = new BufferedReader(new InputStreamReader(
stream,"UTF-8"));
String data = "";
while ((data = inStream.readLine()) != null) {
dataBuffer.append(data);
}
inStream.close();
return dataBuffer.toString();
}