Sending special characters using HttpURLConnection in Java - java

I have a web service and I want to invoke that with "application/x-www-form-urlencoded" content type. The request sometimes contains special characters such as + * - and .... The problem is that destination web service doesn't receive the request perfectly. It receives something like this: "////////////////w==" almost all characters are turned to / . What is the problem?
Here is my code:
URL url = new URL("a-web-service-url");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write("test=/-+*=!##$%^&*()_");
outputStreamWriter.flush();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder;
String line;
for (stringBuilder = new StringBuilder(); (line = bufferedReader.readLine()) != null; stringBuilder = stringBuilder.append(line)) {
;
}
bufferedReader.close();
httpURLConnection.disconnect();
String response = stringBuilder.toString().trim();
The web service receives:
test=////////////////w==

Use URLEncoder to encode the string before sending.
URLEncoder.encode(message, "UTF-8" );
In this case it will be
outputStreamWriter.write(URLEncoder.encode("test=/-+*=!##$%^&*()_", "UTF-8" ));

Related

Download Binary file from SOAP API using Javacode

I am using the below Java code to download the response from SOAP API. Soap API response contains Binary Data stream file. I am able to get the whole response with Binary data. I would need to download only Binary attachment file alone from Soap API.
Output:
enter image description here
Java code
String url = "https://services-sd02.drivecam.com/DCSubmission/EventFileStreamingService.svc";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml");
con.setRequestProperty("SOAPAction",
"http://DriveCam.com/Services/IEventFileStreamingService/GetEventFileById");
String xml = "Input Xml";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString();
String out = responseString;
byte[] stream = out.getBytes();
FileOutputStream out1 = new FileOutputStream("P:/Informatica/data/zd_misc/TgtFiles/Binary_File");
out1.write(stream);
out1.close();
}
}

Error with cURL and java String variable

I'm trying to use glot.io api to compile java code with curl.
I read a text file :
BufferedReader bufferedReader = new BufferedReader(new FileReader("input.txt"));
StringBuffer stringBuffer = new StringBuffer();
String line = bufferedReader.readLine();
while(line != null){
stringBuffer.append(line);
line = bufferedReader.readLine();
}
If I use no quotation marks, I have no problem when I request the url
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Token myToken");
conn.setRequestProperty("Content-Type", "application/json");
String data = "{\"files\": [{\"name\": \"main.java\", \"content\": \"" + stringBuffer.toString() + "\"}]}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(bf.readLine());
But when I use String in my code, the web page return 400 error.
Can you help me ?

Some server garbled when use UrlConnection?

I use below code to post some data,but i find In some server the response string is garbled(not all servers).
URL url = new URL("http://url");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", String_UTF_8);
connection.setRequestProperty("contentType", String_UTF_8);
connection.connect();
PrintWriter out = new PrintWriter(newOutputStreamWriter(connection.getOutputStream(),String_UTF_8));
out.println(json);
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), String_UTF_8));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes());
sb.append(lines);
}
reader.close();
connection.disconnect();
I tried a lot of ways,but all have no effect.
Don't use String#getBytes() it will decode your String using the platform's default charset which means that it is platform dependent. Moreover as you have already decoded your stream content as String using UTF-8 as charset, it is even useless.
Try this instead:
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), String_UTF_8))
) {
String lines;
while ((lines = reader.readLine()) != null) {
sb.append(lines);
}
}

How to add header to HttpRequest of GET method in Java

I have to pass a token as part of validation for each GET request to access RESTful web service. Below is the code I'm using it to access REST api:
public static String httpGet(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
System.out.println("Response code: "+conn.getResponseCode());
throw new IOException(conn.getResponseMessage());
}
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();
return sb.toString();
}
I can't see any such method to set Header conn.setHeader() provided for HttpsURLConnection. It should be something like X-Cookie: token={token}; please help me to find a way to set header.
You can use:
conn.addRequestProperty("X-Cookie", "token={token}");
or setRequestProperty() also works
You are already setting headers on your request in your code when you do the following:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
I.e. if the service you are communicating with requires that you send your token in the "X-Cookie" header you can simply do the same for that header:
conn.setRequestProperty("X-Cookie", "token={token}");

return StringBuffer array

I'm using StringBuffer to send and receive variables from a web service.
My code is:
// Create connection
url = new URL(urlSCS + "/login");
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", "pl-PL");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
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);
response.append('\r');
}
rd.close();
How can I change this code to be able to receive Array instead of String?
The request which I get from the web service is like this: {"var", "var"}.
This might help
http://www.coderanch.com/t/393008/java/java/explode-Java
Remember to cut the response from {} using response.substring()!
look at:
String partsColl = "A,B,C";
String[] partsCollArr;
String delimiter = ",";
partsCollArr = partsColl.split(delimiter);
you will have your responses in "" so substring them then.
Good luck!

Categories