HttpGet not recognizing url - java

So I'm using the code below from a different older post, but having trouble with one part, the line for: HttpGet request = new HttpGet(url); doesn't work. In the url spot I put something like www.stackoverflow.com, but that one part won't let the code compile. I'm basically trying to pull text writing from an html website. The complete code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(www.stackoverflow.com);
HttpResponse response = client.execute(request);
String html = "Toronto-GTA";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
}

HTTPGet expects an URL or a string, so try to change your request line into:
HttpGet request = new HttpGet("http://www.stackoverflow.com/");

Use a string of the form:
[scheme:][//authority][path][?query][#fragment]
i.e. "http://www.stackoverflow.com"

Try this: HttpGet request = new HttpGet("www.stackoverflow.com");

Adding to above given answers surround your code with try and catch statements to catch the exceptions.
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("www.stackoverflow.com");
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line, html = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
}
catch(Exception e){
//Do something here like printing the stacktrace
}

Related

In CKAN, I am trying to upload a file using java client.But getting error code "400" but not showing any error log

In CKAN, I am trying to upload a file using java client.But getting error code "400" but not showing any error log. I have done CKAN setup locally on Centos7 system. Please help if any suggestion, thanks :)
protected String MultiPartPost(String path, String data)
throws CKANException {
String body = "";
String CKANrepos = "http://172.21.9.118:5000";
String CKANapiHeader="X-CKAN-API-Key";
String CKANapi = "api key";
//1st part
String generatedFilename=null;
HttpClient httpclient = new DefaultHttpClient();
String filename = "test.txt";
try {
// create new identifier for every file, use time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyyMMMddHHmmss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date=dateFormatGmt.format(new Date());
generatedFilename=date +"/"+filename;
HttpGet getRequest = new HttpGet(this.CKANrepos+ "/api/storage/auth/form/"+generatedFilename);
getRequest.setHeader(CKANapiHeader, this.CKANapi);
HttpResponse response = httpclient.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode!=200){
throw new IllegalStateException("File reservation failed, server responded with code: "+statusCode+
"\n\nThe message was: "+body);
}
}catch (IOException ioe) {
System.out.println(ioe);
} finally {
httpclient.getConnectionManager().shutdown();
}
//2nd part
File file = new File("D:\\test.txt");
httpclient = new DefaultHttpClient();
try {
FileBody bin = new FileBody(file,"text/html");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", bin);
reqEntity.addPart("key", new StringBody(generatedFilename));
HttpPost postRequest = new HttpPost(this.CKANrepos+"/storage/upload_handle");
postRequest.setEntity(reqEntity);
postRequest.setHeader(CKANapiHeader, this.CKANapi);
HttpResponse response = httpclient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String line;
while ((line = br.readLine()) != null) {
body += line;
}
if(statusCode!=200){
System.out.println("statusCode ==" +statusCode);
}
}catch (IOException ioe) {
System.out.println(ioe);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
}

Get Website text from URL into String (Android)

first of all I have to say that I'm a beginner in Android programing and not very experienced in general programing at all. But now I decided to make a little app for my private use.
In my app I need to get some Text from a given URL into a string. I found some methods on the web and personalized them a bit. But there is something wrong because when I run the app with the Android Eclipse emulator it says "Unfortunately, xxx_app has stopped.".
Here is my code:
public String getURLtext(String zielurl) throws IllegalStateException, IOException{
String meineurl = zielurl;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(meineurl);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
return result;
}
And this is the method where I want to show the output string in my EditText text1.
public void test(View view) throws InterruptedException, ExecutionException, IllegalStateException, IOException {
EditText text1 = (EditText)findViewById(R.id.textfeld);
String teststring = getURLtext("http://ephemeraltech.com/demo/android_tutorial20.php");
text1.setText(teststring);
}
I would be happy if anyone can help me with this.
Thanks!
Your code looks good until you get the HTTPResponse, the bottom part (response to string) can be optimized a lot. It's also worth noticing that Android won't let you to do network operation on the main thread, so please consider using an AsyncTask to execute your http GET operation.
public String getURLtext(String zielurl) throws IllegalStateException, IOException
{
String result = ""; // default empty string
try
{
String meineurl = zielurl;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(meineurl);
HttpResponse response = httpClient.execute(httpGet, localContext);
InputStream is = response.getEntity().getContent();
result = inputStreamToString(is).toString();
}
catch (Exception ex)
{
// do some Log.e here
}
finally
{
return result;
}
}
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return full string
return total;
}

Unknown host exception, Apache HttpClient, Java, wunderground

I've been stuck on this particular dilemma for some time, I have scoured the site and found some help, but not to my particular issue. I'm trying to connect to a website to extract JSON data from it. The host is what i'm not sure about:
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("www.wunderground.com", 80);
HttpGet httpGet = new HttpGet(urllink); // urllink is "api.wunderground.com/api/my_key/conditions/forecast/hourly/alerts/q/32256.json"
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(targetHost, httpGet);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (Exception e) {
// print stacktrace
return null;
} finally {
try {
instream.close();
} catch (Exception e) {
// print stacktrace
return null;
}
}
return stringBuilder.toString();
The host could either be www.wunderground.com or api.wunderground.com, but when I try either of them i get Unknown host exception.
I found the error. It was that I did not have the permission in the android manifest!
The call should be similar to:
http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json
or as stated in the API,
GET http://api.wunderground.com/api/Your_Key/features/settings/q/query.format

HttpResponse and BufferedReader

I am trying to read the buffer (android application) and set the value to my TextView 'httpStuff'. But i dont think i am getting some response from the URI.
I don't get any runtime errors. I tried many flavour of the same logic. Nothing seems to be working.
INTERNET permission is already set in the manifest. SdkVersion="15". Any help ?
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
httpStuf.setText( in.readLine());
I think you are missing the while loop and also, when you say only in.readLine(), may be it is returning you an empty line from the response, though it is having enough data.So make sure to read the reader entirely like this and check its contents.
while ((line = rd.readLine()) != null) {
httpStuf.setText(line+"\r\n");
}
Hope this will help you.
This code worked for me
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}
try to get the status code of response and Then you can compare with the (HTTP status)
int responseCode=response.getStatusLine().getStatusCode()
I am using this method to simply catch the HTTP response and it works fine for me.
public String httpGetResponse(String url) {
try {
Log.i("HTTP Request", "httpGet Request for : " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//get.setHeader("Connection", "keep-alive");
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line + "\n");
}
return str.toString();
} catch (Exception e) {
Log.e("HTTP error", "Error in function httpGetResponse : "
+ e.getMessage());
return null;
}
}

Source Code html doesn't download completly

I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.
Here is the code i use to get source code:
String SourceCode(String adres) throws IllegalStateException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(adres);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()
)
);
String result = "";
while(reader.readLine() != null)
{
result += reader.readLine();
}
reader.close();
return result;
Thank you for help:)
You skip one line each time. should be
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
return result.toString();
BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.

Categories

Resources