I need to write a small tool in JAVA which will translate text from English to French using the Google translate API. Everything works but I have an apostrophe decoding problem.
Original text:
Inherit Tax Rate
Text translated with Google translate API:
Taux d' imposition hérité
How it should be:
Taux d'imposition hérité
This is my translate method(sorry for the long method):
private String translate(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + sKey + "&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream googleStream;
if (conn.getResponseCode() == 200) {
googleStream = conn.getInputStream(); //success
} else
googleStream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
I'm using an XML writer to write the text and first I though that this has a problem, but I observed that the text is returned like this in the stream so I introduced the encoding parameter when I initialise the InputStreamReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream, "UTF-8"));
But I receive the string with the same problem. Any ideas about what I can do?
I think this problem is solved by using the format parameter (docs). It defaults to html, but you can change it to text to receive unencoded data. Your request should look like this:
String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + sKey + "&q=" + encodedText + "&target=" + to + "&source=" + from + "&format=text";
Related
I'm using api to get xml.
but English text is okay to get xml
and also number text is okay
however korean text can't get
this is my code
StringBuffer result = new StringBuffer();
try {
String urlstr = "https://openapi.gg.go.kr/OrganicAnimalProtectionFacilit?" +
"KEY=secret" +
"&Type=xml" +
"&pIndex=1"+
"&pSize=100";
URL url = new URL(urlstr);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), StandardCharsets.UTF_8 ));
String returnLine;
result.append("<xmp>");
while((returnLine = br.readLine())!=null) {
result.append(returnLine+"\n");
}
urlconnection.disconnect();
}catch(Exception e) {
e.printStackTrace();
}
return result+"</xmp>";
I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...
InputStream in = address.openStream();
URL url = new URL("://www.mydomain.com/?param1=NÃO¶m2=NÃO");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
But when i am trying to put the result into StringBuilder the NÃO Special character à is getting escaped
How to bring it with out losing the char set value ?
I believe you want to use URLEncoder.encode(String, String) to encode your parameter like
try {
String value = URLEncoder.encode("NÃO", "utf-8");
String url = "://www.mydomain.com/?param1=" + value + "¶m2="
+ value;
System.out.println(url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Output is
://www.mydomain.com/?param1=N%C3%83O¶m2=N%C3%83O
I'm trying to send png to server using http get request. I'm using code below to to so.
String encoding (on client):
byte[] bytes = Files.readAllBytes(Paths.get(chosenFile.getPath()));
String image = new String(bytes, "ISO-8859-1");
Then I send http get request to server with String image.
Server receive it but I get image that is not the same as one I sent (I can't open one I received). I'm using URLEncoder.encode(image, "ISO-8859-1") to encode url for http get request. When I use URLEncoder.encode(image, "UTF-8"), the same happens.
Why this doesn't work?
Is there any better way of doing this kind of stuff?
UPD #0
Code for sending an image:
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser= new JFileChooser();
int choice = chooser.showOpenDialog(this);
if (choice != JFileChooser.APPROVE_OPTION) return;
File chosenFile = chooser.getSelectedFile();
try {
byte[] bytes = Files.readAllBytes(Paths.get(chosenFile.getPath()));
String image = new String(bytes, "ISO-8859-1");
if(image != null){
boolean allsent = false;
long k = 0;
String query = "0";
while(!allsent){
String s = image;
String send = "";
long q;
if(k+400>image.length()){
q=image.length();
allsent=true;
}
else q = k+400;
for(long i=k;i<q;i++)
send+=s.charAt((int) i);
System.out.println(send);
String response = new HTTP().GET(Constants.ADDRESS_ADDIMAGE
+ "?" + Constants.USERNAME + "=" + URLEncoder.encode(user, "UTF-8")
+ "&" + Constants.IMAGE + "=" + URLEncoder.encode(send, "ISO-8859-1")
+ "&" + Constants.QUERY + "=" + URLEncoder.encode(query, "UTF-8"));
k+=400;
query="1";
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Note:
HTTP().GET() invokes standard http get.
UPD #1
Server code
#GET
#Path("/addimage")
#Produces(MediaType.APPLICATION_JSON)
public String addImage(#QueryParam("username") String uname, #QueryParam("image") String image, #QueryParam("query") String query) {
if(query.equals("0")){
String s = image;
JDBC.addImage("ABase", "MarketLogin", "image", uname, s);
}
else{
String s = JDBC.selectDB("ABase", "MarketLogin", "image", uname, "username") + image;
JDBC.addImage("ABase", "MarketLogin", "image", uname, s);
}
return "1";
}
Note:
JDBC is class for updating mysql DB. Server is expecting String encoded by ISO-8859-1.
How about using a HttpURLConnection and sending bytes instead of strings.
HttpURLConnection connection;
ByteArrayOutputStream baos;
try {
URL url = new URL("http://www.somewebsite.com");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod("POST");
baos = new ByteArrayOutputStream();
baos.write(bytes); // your bytes here
baos.writeTo(connection.getOutputStream());
}
finally {
if(baos != null)
baos.close();
if(osw != null)
osw.close();
if(connection != null)
connection.disconnect();
}
I want to ask a question about Java. I have use the URLConnection in Java to retrieve the DataInputStream. and I want to convert the DataInputStream into a String variable in Java. What should I do? Can anyone help me. thank you.
The following is my code:
URL data = new URL("http://google.com");
URLConnection dataConnection = data.openConnection();
DataInputStream dis = new DataInputStream(dataConnection.getInputStream());
String data_string;
// convent the DataInputStream to the String
import java.net.*;
import java.io.*;
class ConnectionTest {
public static void main(String[] args) {
try {
URL google = new URL("http://www.google.com/");
URLConnection googleConnection = google.openConnection();
DataInputStream dis = new DataInputStream(googleConnection.getInputStream());
StringBuffer inputLine = new StringBuffer();
String tmp;
while ((tmp = dis.readLine()) != null) {
inputLine.append(tmp);
System.out.println(tmp);
}
//use inputLine.toString(); here it would have whole source
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
}
This is what you want.
You can use commons-io IOUtils.toString(dataConnection.getInputStream(), encoding) in order to achieve your goal.
DataInputStream is not used for what you want - i.e. you want to read the content of a website as String.
If you want to read data from a generic URL (such as www.google.com), you probably don't want to use a DataInputStream at all. Instead, create a BufferedReader and read line by line with the readLine() method. Use the URLConnection.getContentType() field to find out the content's charset (you will need this in order to create your reader properly).
Example:
URL data = new URL("http://google.com");
URLConnection dataConnection = data.openConnection();
// Find out charset, default to ISO-8859-1 if unknown
String charset = "ISO-8859-1";
String contentType = dataConnection.getContentType();
if (contentType != null) {
int pos = contentType.indexOf("charset=");
if (pos != -1) {
charset = contentType.substring(pos + "charset=".length());
}
}
// Create reader and read string data
BufferedReader r = new BufferedReader(
new InputStreamReader(dataConnection.getInputStream(), charset));
String content = "";
String line;
while ((line = r.readLine()) != null) {
content += line + "\n";
}