how can i access to number of search result in bing search?
i found this thread:
How to get number of search result from Bing API
in this thread i understand that i should use d->results[0]->WebTotal
but how can i use this line in java?
public static void main(String[] args) throws Exception {
//term1
String searchText = "is";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="WOCKN8uXArczOkQq5phtoEc7usB0kDoPTnbqn0sKWeg";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
//conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
//text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html
I found the answer:
public static void main(String[] args) {
String searchText = "searchtext";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="key_ID";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
//write json to string sb
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
//find webtotal among output
int find= sb.indexOf("\"WebTotal\":\"");
int startindex = find + 12;
int lastindex = sb.indexOf("\",\"WebOffset\"");
System.out.println(sb.substring(startindex,lastindex));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I'm trying to use the PUBG API (popular PC game) and I am having trouble using JSON (first time). I just want to access figures that are further embedded within the JSON array.
I have tried accessing index numbers of the JSON array but it seemed to not work
Here is the JSON im trying to use
![1]: https://imgur.com/dGy4k9t "json"
Here is what I've tried
public static void main(String[] args) {
StringBuffer response = new StringBuffer();
try {
URL url = new URL("https://api.pubg.com/shards/steam/seasons/lifetime/gameMode/squad-fpp/players?filter[playerIds]=account.0165929b76b147d1a453bbfd21a58b4b");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Accept", "application/vnd.api+json");
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("============");
System.out.println("============");
JSONObject myResponse = new JSONObject(response.toString());
JSONArray arr = myResponse.getJSONArray("data");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("type");
System.out.println("name: " + post_id);
}
}
I get this error when I consume the REST Api of Zimbra on Android: must Athenticate java.lang.RuntimeException: Failed : HTTP error code : 401
at ZimbraREST.main(ZimbraREST.java:33). However I am absolutely sure that my login and my password are the good ones and my code was working perfectly fine yesterday, and I did not modify any important stuff linked to this code. This code should get me an xml file that I use to get sync calendar on my app. Thanks for your help. Here is my code:
#Override
protected Void doInBackground(Integer... integers) {
System.out.println("15email_adress=" + email_adress);
System.out.println("15password=" + password);
String dayStart = String.valueOf(integers[0]);
String monthStart = String.valueOf(integers[1]);
String yearStart = String.valueOf(integers[2]);
String dayEnd = String.valueOf(integers[3]);
String monthEnd = String.valueOf(integers[4]);
String yearEnd = String.valueOf(integers[5]);
String[] strings = {dayStart, monthStart, yearStart, dayEnd, monthEnd, yearEnd};
int k = 0;
for(String s: strings){
if(s.length() < 2){
strings[k] = "0" + s;
}
k++;
}
dayStart = strings[0];
monthStart = strings[1];
yearStart = strings[2];
dayEnd = strings[3];
monthEnd = strings[4];
yearEnd = strings[5];
try {
URL url = new URL("https://zmail.insa-lyon.fr/home/" + email_adress + "/Calendrier%20Cocktail?fmt=xml&start=" +
monthStart +
"/" +
dayStart +
"/" +
yearStart +
"&end=" +
monthEnd +
"/" +
dayEnd +
"/" +
yearEnd);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_adress, password.toCharArray());
}
});
conn.setRequestMethod("GET");
conn.setRequestProperty("--user", email_adress + ":" + password);
if (conn.getResponseCode() != 200) {
System.out.println("15erreur=" + url.toString());
System.out.println("15erreur=" + conn.getResponseMessage());
System.out.println("15erreur=" + conn.getRequestMethod());
return null;
}
System.out.println(conn.getResponseMessage());
InputStreamReader inputStreamReader = new InputStreamReader((conn.getInputStream()));
BufferedReader br = new BufferedReader(inputStreamReader);
String output;
StringBuilder xml = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
xml.append(output);
}
inputStreamReader.close();
br.close();
conn.disconnect();
System.out.println(xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml.toString())));
rootElement = document.getDocumentElement();
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
return null;
}
Ok so I had to authenticate the user with the code below:
// Authentication part -------------------
String userpass = email_adress + ":" + password;
conn.setRequestProperty("X-Requested-With", "Curl");
String basicAuth = "Basic " + new String(android.util.Base64.encode(userpass.getBytes(), android.util.Base64.DEFAULT));
conn.setRequestProperty("Authorization", basicAuth);
// ----------------------------------------
I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.
Code:
String recipeName = this.recipe.getName().replace(" ", "%20");;
String recipeIngredients = this.recipe.getIngredients().replace(" ", "%20");;
String recipeInstructions = this.recipe.getInstructions().replace(" ", "%20");;
String recipeUserName = this.recipe.getUserName().replace(" ", "%20");;
int recipeRate = this.recipe.getRate();
int recipeAmountOfRate = this.recipe.getAmountOfRates();
String link = "http://***My_Site***/createRecipe.php?recipeName="+recipeName+"&recipeIngredients="+recipeIngredients
+"&recipeInstructions="+recipeInstructions+"&recipeUserName="+recipeUserName+"&recipeRate="+recipeRate+
"&recipeAmountOfRate="+recipeAmountOfRate;
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
Log.e("Error", sb.toString());
} catch(Exception e) {
Log.e("Error", e.toString());
} finally {
urlConnection.disconnect();
}
}
But i get the error:
E/Error: java.io.EOFException
Why is that?
in previous requests the request went good.
Doed the URL request too long?
I'm triyng to send POST request to the server. The following java code working for PC application, but doesn't work on my Android application. The Iternet permission is added, so, what I have to do to send this post, and what other methods and libraries I have to use to replace this code for Android?
String hostname = "xxxxxxx.box";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
String SID = new classSID("xxxxxx").obtainSID();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
String str = "enabled=on&username="+givenName+"&email="+givenEmail+"&password="+givenPassword+"&frominternet=on&box_admin_rights=on&phone_rights=on&homeauto_rights=on&uid=&sid="+SID+"&apply=";
////////////////////////////////////////////////////////////////////////////////////////////
wr.write("POST /system/boxuser_edit.lua HTTP/1.1");
wr.write("Host: xxxxxx:80" + "\r\n");
wr.write("Accept: text/html" + "\r\n");
wr.write("Keep-Alive: 300" + "\r\n");
wr.write("Connection: Keep-Alive" + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded"+"\r\n");
wr.write("Content-Length: "+str.length()+"\r\n");
wr.write("\r\n");
wr.write(str+"\r\n");
wr.flush();
////////////////////////////////////////////////////////////////////////////////////////////
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(),"UTF-8"));
String line;
while((line = rd.readLine()) != null)
Log.v("Response", line);
wr.close();
rd.close();
sock.close();
}
The issue is with creating socket on port 80. You need root permission to access port < 1024 in android. See issue
Try this: and consider using an IP instead of hostname because your android device might nto be able to resolve a local hostname
private static final String UTF_8 = "UTF-8";
/**
* #param hostNameOrIP
* : the host name or IP<br/>
* #param webService
* : the web service name<br/>
* #param classOrEndPoint
* : the file or end point<br/>
* #param method
* : the method being called<br/>
* #param parameters
* : the parameters to be sent in the message body
* #return
*/
public static String connectPOST(final String url, final HashMap<String, String> parameters) {
final StringBuilder postDataBuilder = new StringBuilder();
if (null != parameters) {
for (final HashMap.Entry<String, String> entry : parameters.entrySet()) {
if (postDataBuilder.length() != 0) {
postDataBuilder.append("&");
}
postDataBuilder.append(entry.getKey()).append("=").append(entry.getValue());
}
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
out = conn.getOutputStream();
final byte[] postData = postDataBuilder.toString().getBytes(UTF_8);
out.write(postData);
out.flush();
out.close();
final int responseCode = conn.getResponseCode();
if ((responseCode == 401) || (responseCode == 403)) {
// Authorization Error
Log.e(TAG, "Authorization error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if (responseCode == 404) {
// Authorization Error
Log.e(TAG, "Not found error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if ((responseCode >= 500) && (responseCode <= 504)) {
// Server Error
Log.e(TAG, "Internal server error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Internal Server Error in " + method +
// "("
// + postDataBuilder.toString() + ")");
return null;
}
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while ((null != (line = buff.readLine())) && !"null".equals(line)) {
text.append(line + "\n");
}
buff.close();
buff = null;
in.close();
in = null;
conn.disconnect();
conn = null;
} catch (final Exception e) {
Log.e(TAG, "Exception while connecting to " + url + " with parameters: " + postDataBuilder + ", exception: " + e.toString() + ", cause: "
+ e.getCause() + ", message: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
if (null != out) {
try {
out.close();
} catch (final IOException e1) {
}
out = null;
}
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
final String temp = text.toString();
if (text.length() > 0) {
Log.i(TAG, "Success in " + url + "(" + postDataBuilder.toString() + ") = " + temp);
return temp;
}
Log.w(TAG, "Warning: " + url + "(" + postDataBuilder.toString() + "), text = " + temp);
return null;
}