Can anyone please share some java codes for getting response from google search. I am stuck over "Result=403" and "Connect failed:Network is unreachable".Please check my coding below. I'll be thankful if anyone can help me.(I have obtained API key and custom search engine id).
Thanks.
public class MainActivity extends AppCompatActivity {
private String SearchUrl = "https://www.googleapis.com/customsearch/v1?key=AIzaSyByPqZ3jZG5KOsg7EmxSGTHhp3SIL7dyIk&cx=012845902157700116531:oqktayhycq4&q=";
private String SearchItem = "android";
private String SearchQuery = SearchUrl + SearchItem + "&alt=json";
TextView searchResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchResult = (TextView) findViewById(R.id.result);
new JsonSearchTask().execute();
}
private class JsonSearchTask extends AsyncTask<Void, Void, Void> {
String searchResultString = "";
@Override
protected Void doInBackground(Void... params) {
try {
searchResultString = ParseStringResult (sendQuery(SearchQuery));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
searchResult.setText(searchResultString);
super.onPostExecute(aVoid);
}
}
private String sendQuery(String query) throws IOException{
String result="";
URL sUrl=new URL(query);
HttpURLConnection httpURLConnection=(HttpURLConnection) sUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Accept", "application/json");
//if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
InputStreamReader inputStream=new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader=new BufferedReader(inputStream,8192);
String line=null;
while((line=bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
// }
return result;
}
private String ParseStringResult(String json) throws JSONException{
String ParseResult="";
JSONObject jsonObject= new JSONObject(json);
JSONObject jsonObject_responseData=jsonObject.getJSONObject("responseData");
JSONArray jsonArray_result=jsonObject_responseData.getJSONArray("results");
ParseResult+="Google Search for :"+SearchItem+"\n";
ParseResult+="Number of result returned ="+jsonArray_result.length()+"\n\n";
for(int i=0;i<jsonArray_result.length();i++){
JSONObject jsonObject_i=jsonArray_result.getJSONObject(i);
ParseResult+="title"+jsonObject_i.getString("title")+"\n";
ParseResult+="content"+jsonObject_i.getString("content")+"\n";
ParseResult+="url"+jsonObject_i.getString("url")+"\n\n";
}
return ParseResult;
}
}