Try Catch unexpected token - java

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 { ... }
}
}

Related

Apache HttpAsyncClient Reading of Response?

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.

Is this correct approach to submitting JSON via HTTP POST to a java Web Server?

I construct the JSON Object
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
I Execute an AsyncTask
new HTTPtoServer().execute(jsonobj);
The AsyncTask looks like this:
private class HTTPtoServer extends AsyncTask<JSONObject, Void, String> {
#Override
protected String doInBackground(JSONObject... params) {
//Prepare HTTP Post Client
DefaultHttpClient myClient = new DefaultHttpClient();
HttpPost myPost = new HttpPost(ElasticBeanStalkEndpoint);
StringEntity se = null;
Log.v("TEST","TEST");
try {
se = new StringEntity(params[0].toString());
Log.v("MY SE", se.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
myPost.setEntity(se);
HttpResponse httpresponse = null;
try {
httpresponse = myClient.execute(myPost);
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
#Override
protected void onPostExecute(String s) {
Log.v("MY STRING", s);
}
}
However my JSON Object appears to never be "sending"?
Or maybe it is, but in an incorrect format?
The Java Tomcat server doesn't seem to be doing anything with the data?
My StringEntity results in :
org.apache.http.entity.StringEntity#528111f8
When I do se.toString()... Is this correct?
I seem to be a bit confused.
SERVER CODE:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
PrintWriter out = response.getWriter();
String action = jsonObject.getString("action");
log("action: " + action);
JSONObject requestObject = jsonObject.getJSONObject("request");
log("requestObject: " + requestObject);
if (action.equalsIgnoreCase("put-point")) {
putPoint(requestObject, out);
} else if (action.equalsIgnoreCase("get-point")) {
getPoint(requestObject, out);
} else if (action.equalsIgnoreCase("update-point")) {
updatePoint(requestObject, out);
} else if (action.equalsIgnoreCase("query-rectangle")) {
queryRectangle(requestObject, out);
} else if (action.equalsIgnoreCase("query-radius")) {
queryRadius(requestObject, out);
} else if (action.equalsIgnoreCase("delete-point")) {
deletePoint(requestObject, out);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString());
}
}
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString());
AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName"));
PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue);
putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue);
PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest);
printPutPointResult(putPointResult, out);
}
Try like that.
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
new SendData().execute(jsonobj.toString());
public class SendData extends AsyncTask<String, Integer, Double>{
String response="";
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
}
public void postData(String jsondata) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsondata));
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse res = httpclient.execute(httpPost);
InputStream content = res.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println("response from server"+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
SERVER SIDE-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsondata=request.getParameter("json");
//now parse your data from json
try {
JSONObject JsonObject=new JSONObject(jsondata);
JSONObject object=JsonObject.getJSONObject("request");
String action=object.getString("action");
String lng=object.getString("lng");
String lat=object.getString("lat");
String rangeKey=object.getString("rangeKey");
String schoolName=object.getString("schoolName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this will help you...!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PROJECT_ID, params[0]));
nameValuePairs.add(new BasicNameValuePair(BROKER_ID,params[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder responseJsonStr = new StringBuilder();
while ((output = br.readLine()) != null) {
responseJsonStr.append(output);
}
String queryString = Utils.getQueryString(nameValuePairs);
System.out.println("Query String "+URL +"&"+queryString);
//System.out.println("response Json String "+responseJsonStr );
if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
responseJsonStr.insert(0,"[");
responseJsonStr.append("]");
}
try this:
public String getJson(Context applicationContext,String url) {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("response_key",PrefernceSettings.getRestKey()));
nameValuePair.add(new BasicNameValuePair("response_request","auto_payments"));
Log.e("",String.valueOf(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
if(is != null){
result = convertInputStreamToString(is);
Log.e("result", result);
}else{
result = "Did not work!";
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while((line = bufferedReader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Try using this function:
public boolean postJSON(JSONObject jsonobj) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost("YOUR URL HERE");
StringEntity se = new StringEntity(jsonobj.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
//Send Http request
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
String resonseStr = EntityUtils.toString(entity);
return getResponse(resonseStr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
0D
where getResponse is a function that gets the response string and parses it and returns true or false according to how you define the web service.

Android: JSON isn't working, Log.e returns a null

I am trying to get the USD average price 30d for bitcoins from here: http://api.bitcoincharts.com/v1/weighted_prices.json. The Json code I have does not work in the try/catch, and the error is a null (I have tried looking into other questions but all of them seem to return errors, whereas mine just returns a null):
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogewidget);
TextView btctest = (TextView) findViewById(R.id.title);
//Create a new HTTP Client
DefaultHttpClient httpclient = new DefaultHttpClient();
//Setup the get request
HttpPost httppost = new HttpPost("http://api.bitcoincharts.com/v1/weighted_prices.json");
//Depending on web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
JSONObject jObject = new JSONObject(result);
JSONObject jsubObject = jObject.getJSONObject("USD");
String btcjson = jsubObject.getString("30d");
btctest.setText(btcjson);
} catch (Exception e) {
e.printStackTrace();
Log.e("error", "" + e.getMessage());
btctest.setText("Error " + e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
}
}
Any help would be appreciated! Thanks.
Try this code.
private void get_value(String php) {
String responseString = null;
try{
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Toast.makeText(getApplicationContext(),responseString,1000).show();
//The below code is for Separating values.It may varies according with your result
JSONArray ja = new JSONArray(responseString);
int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name"));
} catch(Exception e) {
}
}

HTTP POST request with JSON String in JAVA

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();
}
}

How to get text from website to string?

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;
}

Categories