How to get XML from this URL into String on Android? I was trying to do it with tutorials, but no way was successful. Here is my code:
public String getXmlFromUrl(String url) {
String text = "";
try {
HttpGet get = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
InputStream inputStream = response.getEntity().getContent();
String line = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
while ((line = rd.readLine()) != null) {
text += line;
}
} catch (Exception e) {
e.printStackTrace();
}
return text;
}
Related
private void init() {
#Reactor
ioReactorConfig = IOReactorConfig.custom()
.setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setConnectTimeout(30000)
.setSoTimeout(30000)
.build();
try {
ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
} catch (IOReactorException e) {
e.printStackTrace();
//TODO handle exception
}
connManager = new PoolingNHttpClientConnectionManager(ioReactor);
httpClient = HttpAsyncClients.custom().setConnectionManager(connManager).build();
}
private ZCResponse httPost(URI uri, Object object,List<NameValuePair> params, Map<String,String> headers) {
HttpPost postRequest = new HttpPost(uri);
HttpResponse httpResponse = null;
try {
addHeaders(postRequest,headers);
addPostParams(postRequest,object,params);
Future<HttpResponse> futureResponse = httpClient.execute(postRequest, null);
httpResponse = futureResponse.get();
response = **readResponse(httpResponse);**
}
private String readResponse(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
I have the following doubts about the code using Apache Http Async client
What is the role of reactor with NPoolingConnectionManager.
Currently, the response body is read from from post request's stream.And not using NIO or non-blocking way of reading the response body.Is it the right way.
I've build app android uses http client to get content from URL,
String getRequest(String SUrl){
String vResult = "TEST";
//SUrl result of "http://mydomain.com/file.php?var=21"
HttpClient client = new DefaultHttpClient();
HttpGet request;
try{
request=new HttpGet(SUrl);
HttpResponse response = client.execute(request);
vResult=request(response);
}catch(Exception ex){
Log.e("From Server", ex.getMessage());
}
return vResult;
}
public static String request(HttpResponse response){
String result = "";
try{
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 + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
in android gingerbread the code above work fine get content from server,but in jelly bean the code result log like this
java.lang.NullPointerException: println needs a message
why i get null in jelly bean even i already declare all variable?
thanks
Try this..
catch(Exception ex){
Log.e("From Server", ""+ex.printStackTrace());
}
I have to make a http Post request using a JSON string I already have generated.
I tried different two different methods :
1.HttpURLConnection
2.HttpClient
but I get the same "unwanted" result from both of them.
My code so far with HttpURLConnection is:
public static void SaveWorkflow() throws IOException {
URL url = null;
url = new URL(myURLgoeshere);
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
DataOutputStream output = null;
DataInputStream input = null;
output = new DataOutputStream(urlConn.getOutputStream());
/*Construct the POST data.*/
String content = generatedJSONString;
/* Send the request data.*/
output.writeBytes(content);
output.flush();
output.close();
/* Get response data.*/
String response = null;
input = new DataInputStream (urlConn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
}
My code so far with HttpClient is:
public static void SaveWorkflow() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myUrlgoeshere);
StringEntity input = new StringEntity(generatedJSONString);
input.setContentType("application/json;charset=UTF-8");
postRequest.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Where generated JsonString is like this:
{"description":"prova_Process","modelgroup":"","modified":"false"}
The response I get is:
{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}
Any idea please?
Finally I managed to find the solution to my problem ...
public static void SaveWorkFlow() throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURLgoesHERE);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}
Another way to achieve this is as shown below:
public static void makePostJsonRequest(String jsonString)
{
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("Ur_URL");
postRequest.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
//System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//System.out.println(builder.toString());
//System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This code gives me an error of unexpected token on the try and catch. What is wrong?
public class WeatherTest
{
String weatherurl = "http://weather.yahooapis.com/forecastrss?w=35801&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(weatherurl);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null)
{
stringBuilder.append(stringReadLine + "\n");
}
String qResult = stringBuilder.toString();
}
catch (IOException ie)
{
ie.printStackTrace();
}
}
Your try/catch block is not inside a method.
You can place it in a method, and call the method.
public class WeatherTest {
String weatherurl = "http://weather.yahooapis.com/forecastrss?w=35801&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(weatherurl);
public void myMethod() {
try { ... }
catch { ... }
}
}
i have a simple JSON feed which returns an image path, and a set of coordinations. The "coords" can have an unlimited set of coordinations. In my example below it only has 3 set.
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
How would i use GSON to parse this? How do I build the class for this?
Thanks
You're going to have a hard time with that because it's not valid JSON.
http://jsonlint.com/
If it were valid JSON such as ...
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
I believe GSON could parse coords to a map of <String, ArrayList<Integer>> but I'd need to try it to make sure.
Add the gson-1.7.1.jar file and write this class to get the required JSONObject or JSONArray from the url.
public class GetJson {
public JSONArray readJsonArray(String url) {
String read = null;
JSONArray mJsonArray = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonArray = new JSONArray(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonArray;
}
public JSONObject readJsonObject(String url) {
String read = null;
JSONObject mJsonObject = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonObject = new JSONObject(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonObject;
}
}
ENJOY...
Then to parse the JSON see the these tutorials,
Tutorial 1
Tutorial 2
Tutorial 3