I'm developing my client-server application (server is like a servlet and client is an Android app). I have some difficulties sending information between two entities when the message has special chars (ie: 'è' or others)
On client side I use this code to send the message that can contain special chars:
public static String effettuaPOSTServer (String parameters) {
try {
byte [] parametersBytes = parameters.getBytes("UTF-8");
URL url = new URL("http://" + IP_SERVER + ":" + PORT + PATH_SERVLET);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(10000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content_Type", "application/x-www-form-urlencoded; charset=utf-8");
connection.setRequestProperty ("Content-Length", String.valueOf (parametersBytes.length));
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(parametersBytes);
wr.flush();
wr.close();
BufferedReader br = new BufferedReader (new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder ();
String s;
while ((s = br.readLine ()) != null) {
sb.append (s);
sb.append ("\n");
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
on server side I use this code to send the response (also the response can contain special chars like 'è' and others) (I'm in servlet doPost context so I work with HttpServletRequest request and HttpServletResponse response):
PrintWriter pw = response.getWriter();
...
String content = ...; //the string is formatted in JSON format
pw.println (content);
but on both sides I'm unable to receive and manage the correct strings where I have special chars.
I'm trying a lot of solutions on web about encoding/decoding etc. but without successful result.
How can I fix my problem? Thank you!
EDIT:
for example, immagine my request from client as follow (I report the request in GET format to show simply the case):
http://MY_URL:PORT/MY_PATH?parameter1=value1¶meter2=value2¶meter3=èqualcosaacaso
but on server I receive:
parameter1=value1
parameter2=value2
parameter3=Äqualcosaacaso
Related
I have code a java script to consume API response. But I am getting a bad request whenever I am trying to run it.
Kindly help me how to consume API through java.
Here I am trying to generate JWT token....
Please find the code below..
public static void main(String[] args) throws Exception {
URL url = new URL("URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
try {
String jsonData1 = "{\"grant_type\":\"aksa\"}";
String jsonData2 = "{\"username\":\"dkssdsk\"}";
String jsonData3 = "{\"password\":\"xE2w04kC1a7S\"}";
String jsonData4 = "{\"scope\":\"mksssl,/\"}";
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.write(jsonData1.getBytes());
output.write(jsonData2.getBytes());
output.write(jsonData3.getBytes());
output.write(jsonData4.getBytes());``
output.flush();
System.out.println(output);
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));`enter code here`
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
}
}
Your code writes:
{"grant_type":"aksa"}
{"username":"dkssdsk"}
{"password":"xE2w04kC1a7S"}
{"scope":"mksssl,/"}
This is not valid JSON. There are many JSON validators (including web pages you can copy/paste into) you could use to show this.
Test your service using a tool such as Postman. Once you have it working, ensure that your program writes the same content as the body configured in Postman.
I want to get the HTML code of the following Web Page (http://www.studenti.ict.uniba.it/esse3/ListaAppelliOfferta.do) after:
selecting "Dipartimento di Informatica" among Facoltà
selecting "Informatica" (or one of the others available)
clicking "Avvia Ricerca"
I am not very keen in the matter but I noticed the URL of the page stays the same after each selection!?!
Can anyone help describing, possibly in details, how can I do that? Unfortunately I am not expert in web programming.
Many thanks
After some tests, it refresh the pages with a POST request
fac_id:1012 --
cds_id:197 --
ad_id: -- Attività didattica
docente_id: -- Id of the docent selected
data:06/03/2014 -- Date
Anyway you missed the value of Attività ditattica, Docente and Data esame
Just run a HTTP request using HttpURLConnection (?) with this POST args, and with a XML parser read the output of tplmessage table.
Try this tutorial for HTTP request: click.
Try to read this to understand how to parse response: click
An example using the code of the tutorial:
HttpURLConnection connection = null;
try
{
URL url = new URL("http://www.studenti.ict.uniba.it/esse3/ListaAppelliOfferta.do");
connection = (HttpURLConnection) url.openConnection(); // open the connection with the url
String params =
"fac_id=1012&cds_id=197"; // You need to add ad_id, docente_id and data
connection.setRequestMethod("POST"); // i need to use POST request method
connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); // It will add the length of params
connection.setRequestProperty("Content-Language", "it-IT"); // language italian
connection.setUseCaches (false);
connection.setDoInput (true);
connection.setDoOutput (true);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes (params); // pass params
wr.flush (); // send request
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
// close connection if created
if (connection != null)
connection.disconnect();
}
In response you will have the DOM of the page.
Anyway, use Chrome developers tool to get request args:
-- Hi everyone
I have a strange behaviour with sugarcrm.
Here the code that i'm using to set a new entry with REST:
public SugarApi(String sugarUrl){
REST_ENDPOINT = sugarUrl + "/service/v4/rest.php";
json = new GsonBuilder().create();
codec = new URLCodec();
}
SetEntryRequest req = new SetEntryRequest(sessionId, nameValueListSetEntry, myKind.getModuleName());
String response = null;
try {
response = postToSugar(REST_ENDPOINT+"?method=set_entry&response_type=JSON&input_type=JSON&rest_data="+codec.encode(json.toJson(req)));
} catch (RemoteException e) {
System.out.println("Set entry failed. Message: " + e.getMessage());
e.printStackTrace();
} catch (EncoderException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
where postToSugar is:
public String postToSugar(String urlStr) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
if(System.getenv("sugardebug") != null){
System.out.println(sb.toString());
}
return sb.toString();
}
So this code is working fine when the post is small.
the maximum size is the following:
{"id":"8c8801c5-ce3b-093c-ee77-514985c19fe1","entry_list":{"account_id":{"name":"account_id","value":"9b37913b-994b-9bc9-4fbf-500e771d845b"},"status":{"name":"status","value":"New"},
"description":{"name":"description","value":"Ceci est un test \/ TICKET A SUPPRIMER"},"priority":{"name":"priority","value":"P1"},
"name":{"name":"name","value":"test longueur post --------------"},"caseorigin_c":{"name":"caseorigin_c","value":"OnLineForm"},"case_chechindate_c":{"name":"case_chechindate_c","value":"2013-01-12"},"type":{"name":"type","value":"ErrorOnCancel"}}}
but if the post is longer, the server returns:
{"name":"Invalid Session ID","number":11,"description":"The session ID is invalid"}
Any help would be appreciated
I encountered this problem with a request I had where the description field had a new line character. I even urlencoded the newline character and it still gave me the error. Presumably apache on Sugar's server was breaking the request at the newline which meant the sessionID wasn't found.
My solution was to replace all occurances of %0A and %0D with %5Cn.
%0A and %0D are different newline characters and %5Cn becomes \n which is a newline in sugar.
I don't have an extensive list of invalid characters for the rest API.
I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.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(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?
I want to send some information from PHP to Java. Why? Because I have a database on my server, and I get information from my database using PHP scripts.
Now I want to send that information to my client in Java. How can I do that?
I send information from Java to PHP by POST, and it works well, but I don't know how can I do the reverse.
Can you help me?
I saw this code, from a GET connection in Java... is it correct?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: I'm an android developer, not a Java developer...
From exampledepot: Sending POST request (Modified to get the output of your send.php.)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
P.S. This should work fine on Android. :)
(I usually import static java.net.URLEncoder.encode but that's a matter of taste.)