I'm trying to get the data from this google translate API URL:
String sourceLang = "auto";
String targetLang = "en";
String sourceText = "olas";
String urlstring = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + sourceText;
the api url works good on python, but on android i get the filenotfoundexception error.
mabye its because the url download a .txt file instead of showing the data, as u can see:
https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=olas
this is the code i used:
URL url = new URL(urlstring);
HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLconnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
Just add user agent to your httpURLconnection.
HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
httpURLconnection.setRequestProperty("User-Agent","MyAppName/1.0");
Related
I have to call one Rest API of GET request.
When I used emulator of API 24 it working fine. but same code on my phone i.e API 23 and API 18 it give 400 status i.e. bad request.
URL url = new URL(voids[0]);
Log.i("url", voids[0]);
//URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.addRequestProperty("User-Agent", "REST");
System.setProperty("http.keepAlive", "false");
con.setRequestProperty("Accept", "*//*");
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.setAllowUserInteraction(false);
con.setRequestMethod("GET");
responseCode = con.getResponseCode();
System.out.println("Sending get request : " + url);
System.out.println("Response code : " + responseCode);
// Reading response from input Stream
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
System.out.println(response.toString());
Url : http://milk.gall5.com/api/SalePunch?CustomerID=1&Model={"CustomerID":"1","lstSalesPunchDetail":[{"ListManufacturer":[{"ManufactureID":1,"ManufacturerName":"Amul","One":40,"OneByFour":10,"OneByTwo":20,"QtyOne":0,"QtyOneByFour":23,"QtyOneByTwo":330,"visibilityOne":true,"visibilityOneByFour":true,"visibilityOneByTwo":true}],"ProductId":2,"ProductName":"Ton Milk"}]}
Try to encode the Model parameter of your URL first.
You can do that with the URLEncoder.encode() method
I am using HttpUrlConnection to get JSON strings from web, but the response is good for smaller strings but not for larger ones: this is what I am seeing in my app, and this is the data from server to a web page I did not include any HTML from server side.
Here is my code:
URL adr = new URL("http://placeform.tk/forapp.php");
HttpURLConnection connection =(HttpURLConnection) adr.openConnection();
connection.connect();
int rcode = connection.getResponseCode();
Log.d("rcode",Integer.toString(rcode));
if (rcode == HttpURLConnection.HTTP_OK) {
InputStream inputStreamReader = connection.getInputStream();
String c = connection.getHeaderField("content-length");
Reader rd = new InputStreamReader(inputStreamReader);
Log.d("contentsize", Integer.toString(connection.getContentLength()) + c);
chars = new char[connection.getContentLength()];
Log.d("contentsize", Integer.toString((int)connection.getContentLength()) + c);
rd.read(chars);
String output = new String(chars);
use this link and add that class in your project and call webservice from that class. cause that class will build up your response string with use of string builder. have a look at that class. and comment if you have any problem.
I am writing below code to get json string from url and parse json string to get stock info in an android app. My code is given below:
url = new URL(in);
Log.e(STOCK,"comes here ..0 ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream stream = conn.getInputStream();
String dataone = convertStreamToString(stream);
reader = new JSONObject(dataone);
Log.e(STOCK,"comes here ..1 ");
JSONObject data = reader.getJSONObject("data");
previousClose = data.getString("previousClose");
lastPrice = data.getString("lastPrice");
low52 = data.getString("low52");
totalTradedValue = data.getString("totalTradedValue");
Toast.makeText(MainActivity.this,lastPrice,Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,totalTradedValue,Toast.LENGTH_LONG).show();
But I am getting exception after opening url, I have added internet permission in Android Manifest xml.
Im getting the following error on trying to use an web service from google api maps:
{
"error_message" : "Requests to this API must be over SSL.",
"results" : [],
"status" : "REQUEST_DENIED"
}
the url used to invoke the web service:
http://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
method used to call the web service:
enter code here
public static String httpPost(String urlStr) throws Exception {
String novaUrl = urlStr.trim();
novaUrl = urlStr.replaceAll(" ", "+");
novaUrl = novaUrl.replaceAll("\r", "");
novaUrl = novaUrl.replaceAll("\t", "");
novaUrl = novaUrl.replaceAll("\n", "");
URL url = new URL(novaUrl);
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-urldecoded");
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.close();
out.close();
// 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();
Spanned retorno = Html.fromHtml(sb.toString());
return retorno.toString();
}
How to solve this problem?
Thanks.
Try using this URL. Error just because of http and https. https is used for secure line.
https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
Now when you click on this you will get some error like this .. The provided API key is invalid.
For that just provide correct API key that you retrieved from Google Console.
Your given URL :: https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
here key=my_key Here is the problem, please provide correct API key and you problem will be solved.
I want to use assembla apis from android environment for my project.
I am trying to do basic authentication as follow :
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
URL url = new URL("https://www.assembla.com/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setDoOutput(true);
conn.connect();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
I am getting 400 and Bad Request in output.
is there something wrong with URL that i am using or some other thing is going wrong?
It looks like the question was answered here. You need to use Base64.NO_WRAP flag when encoding username-password pair:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.
REST API with HTTP Authentication Output:- I got the result
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", "Basic " + encoding);
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
Content = sb.toString();