Error with cURL and java String variable - java

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 ?

Related

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

Sending special characters using HttpURLConnection in 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" ));

HttpURLConnection "An unexpected error occurred."

From my little knowledge of 500 errors I understand it is a server error. But what could be the root cause behind something like this? Could it be on my end?
The error i'm getting is:
{"status":500,"error":"An unexpected error occurred."}
Could it have to do with my headers i.e missing one? From what i've found from testing the error changes from 400 errors i.e 401 after adding the user agent header.
my code looks as follows:
String url="https://api.gotinder.com/auth";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Host", "host url");
//con.setRequestProperty("content-Length" , "287");
con.setRequestProperty("User-Agent" , "Tinder/4.0.4");
con.setRequestProperty("facebook_token", "token");
//con.setRequestProperty("facebook_id", "id");
System.out.println(con.getResponseCode());
Side note: This is all for educational purpose. I got intrigued.
The problem was I was passing my token as a Property and not a part of the body.
code:
String urlstr = "https://api.gotinder.com/auth";
String params = "facebook_token=" + this.fb_token;
URL url = new URL(urlstr);
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("User-Agent", "Tinder/3.0.4 (iPhone; iOS 7.1; Scale/2.00)");
urlconn.setRequestProperty("Content-Language", "en-US");
OutputStream os = urlconn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.close();
os.close();
if (urlconn.getResponseCode() == 200) {
BufferedReader bR = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while ((line = bR.readLine()) != null) {
responseStrBuilder.append(line);
}
urlconn.getInputStream().close();
JSONObject result = new JSONObject(responseStrBuilder.toString());
user_token = result.getString("token");
System.out.println("User token is: " + user_token);
} else {
System.out.println("Want to print error here had getting data...");
}

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);
}
}

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