In official documentation of Google Translate Api for Java it says that we can use post-method to send more than 2K characters. https://developers.google.com/translate/v2/using_rest
However when I try to translate text more than 2k length I get error 414 (Request-URI Too Large).
StringBuilder sb = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.googleapis.com/language/translate/v2");
String urlParameters = "key=" + apiKey + "&source=" + shortLang1 +
"&target=" + shortLang2 + "&q=" + URLEncoder.encode(lyrics, "UTF-8");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches (false);
connection.addRequestProperty("X-HTTP-Method-Override", "GET");
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
if (connection.getResponseCode() != 200) {
return null;
}
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
UPDATE: I got it, the code above is right. Finally I realize that I got this error not from Google Translate service but from my proxy on Google App Engine.
What the document you linked to is saying is that you use the POST method and you put the parameters into the request body ... not the request URL.
Reference:
How are parameters sent in an HTTP POST request?
Related
I have been trying all day to get a minecraft plugin to allow players on bedrock edition on my geyser sever to (OPTIONALY) sign in to java edition using OAuth2's device code flow. I successfully can get a code and url but when I go to poll the API for a successful login I get "Cross-origin token redemption is permitted only for the 'Single-Page Application'." I've tried adding SPA to my azure app registration but the issue persists. I've tried setting the origin header in my request to "http://localhost" and the issue persist:
here is my code for retrieving the login token:
public static JSONObject pollSignIn(String deviceCode) {
double i = 0;
long previousTime = 0;
while (i <= 60000 /*GeyserFloodgateSkinFix.defaultConfig.requestTimeout*/) {
while (!(System.currentTimeMillis() > previousTime)) {}
previousTime = System.currentTimeMillis();
i++;
if ((i/1000) % 3 == 0) {
try {
URL url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Origin", null);
con.setDoOutput(true);
System.out.println(deviceCode);
String body = String.format(
"grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=%s&device_code=%s",
"[Censored]",
deviceCode
);
byte[] output = body.getBytes(StandardCharsets.UTF_8);
OutputStream os = con.getOutputStream();
os.write(output);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(br.readLine());
}
JSONObject json = new JSONObject(sb.toString());
if (json.getString("token_type").equalsIgnoreCase("Bearer")) {
return json;
}
}
catch (Exception ignored) {
System.out.println(ignored.getMessage());
}
}
}
return null;
}
if it helps heres the code I use to get the token (This works)
public static JSONObject getAuthCode() {
try {
URL url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/devicecode");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
String body = String.format(
"scope=XboxLive.signin%%20offline_access&client_id=%s",
"[Censored]"
);
OutputStream os = con.getOutputStream();
byte[] output = body.getBytes(StandardCharsets.UTF_8);
os.write(output, 0, output.length);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
con.disconnect();
return new JSONObject(sb.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
UPDATE: I managed to fix the above error but now I am getting "The provided value for the input parameter 'scope' is not valid. The scope 'XboxLive.signin offline_access' is not configured for this tenant." Chanfing the tenant to "consumer" throws "The provided value for the input parameter 'device_code' is not valid. Device codes supporting the personal Microsoft Account sign-in audience can only be used for v2 common or consumers tenants"
I'm pretty new to OAuth and am trying to refresh a token using a simple java client. Everything seems to go ok (or I think it does), the problem is I can't tell from the response if it's a good one. The http response code is 200, but when trying to parse the response for access_token, I get a null. Also difficult to troubleshoot is the "raw" response is garbled, or encoded in some way. I was thinking maybe it's byte but it doesn't seem to be. Here's the code:
private static String getClientCredentials() {
String postParams = "grant_type=refresh_token&refresh_token=1234567890";
Pattern pat = Pattern.compile(".*\"access_token\"\\s*:\\s*\"([^\"]+)\".*");
String clientId = "myClientID123";
String clientSecret = "myClientSecret123";
String tokenUrl = "https://www.host.com/oauth2/tenant/token";
String auth = clientId + ":" + clientSecret;
String authentication = Base64.getEncoder().encodeToString(auth.getBytes());
BufferedReader reader = null;
HttpsURLConnection connection = null;
String returnValue = "";
try {
URL url = new URL(tokenUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + authentication);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
connection.setRequestProperty("Connection", "keep-alive");
connection.setDoOutput(true);
OutputStream outStream = connection.getOutputStream();
outStream.write(postParams.getBytes());
outStream.flush();
outStream.close();
System.out.println("Resp code: " + connection.getResponseCode());
System.out.println("Resp message: " + connection.getResponseMessage());
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
while ((line = reader.readLine()) != null) {
out.append(line);
}
String response = out.toString();
Matcher matcher = pat.matcher(response);
if (matcher.matches() && matcher.groupCount() > 0) {
returnValue = matcher.group(1);
}
System.out.println("response: " + response);
System.out.println("returnValue: " + returnValue);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
connection.disconnect();
}
return returnValue;
}
Here's the console output, sorry, I had to screenshot it because the characters didn't paste right:
Response Screenshot
Am I trying something that isn't allowed or is there a way to decode the response so I can run the pattern match to extract only the access_token? Or am I going about it all wrong? Any help is greatly appreciated in advance!
I have a cURL command I want to translate in Java
curl -H "Key: XXX" -d url=http://www.google.com http://myapi.com/v2/extraction?format=json
It works fine.
I started to do in Java: (CODE EDITED, it works)
try {
// POST
System.out.println("POSTING");
URL url = new URL("http://myapi.com/v2/extraction?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Key", "XXX");
String data = "http://www.google.com";
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("url=" +data);
writer.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + data);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("REPOSNE" +response.toString());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
But I don't know how to set my arguments.
Thanks for your help.
Jean
If you mean to set a header field Key with value XXX you can use the setRequestProperty
ie
conn.setRequestProperty("Key", "XXX");
If you want to send data, use
String data = "url=http://www.google.com";
conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
EDIT:-
For posting data as form url encoded, try the following code
String data = "url=" + URLEncoder.encode("http://www.google.com", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
wr.write(data.getBytes());
I am actually using the community plugin in Neo4j and trying to make POST requests through java to query neo4j server.
I am always getting a java.io.IOException: Server returned HTTP response code: 400
While similar calls to the same url work through javascript, but the business logic suggests making calls through java.
Here is my code snippet:
String baseURL="ip_of_server";
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(baseURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os=connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os,Charset.forName("UTF-8"));
System.out.println(url);
Map<String, Object> params = new HashMap<String, Object>();
params.put("query", "start x = node(3) return x");
HashMap<String,String> test3= new HashMap<String,String>();
params.put("params", test3);
ObjectMapper temp = new ObjectMapper();
String testString= temp.writeValueAsString(params);
writer.write(testString);
writer.close();
os.close();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println("Response from server for request : " + url.toString() + " is " );
System.out.println(builder.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Any suggestions?
What it requires is a parser, since '=' etc are converted by the encoding into other characters, hence neo4j throws an error
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 ...?