Parameter passing via httpgetClient - apache-httpclient-4.x

I need to hit the URL and get the response, but through this method I can get only one message whereas I want to pass multiple values as a response.
Here is the method:
public String getOutputFromUrl(String url)
{
Log.d("in getOutputFromUrl", "getOutputFromUrl");
String[] output = null;
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("in UnsupportedEncodingException", e.toString());
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("in geClientProtocolExceptiontOutputFromUrl", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("in getOutputFromUrl", e.toString());
e.printStackTrace();
}
Log.d("in getOutputFromUrl:output===>>", output);
return output;
}
I want the return type of the method to be String[] or object of any class ,but
output = EntityUtils.toString(httpEntity)
This line accepts only a string; no other object or string array, so I can't keep multiple values in this output variable passed as response from the URL link

Related

Transform java object to JSONObject return null on live server

I have a web application (Maven project, JSP/SERVLET, TomCat 8.5.20). The application run perfectly in localhost (same TomCat version), but when i deploy to a live server, the following code doesn't work, the 'x01Json' (JSONObject) variable value be 'null' after i cal the transfromGameToJson() method.
Game init servlet, where i set JSON in request
X01Game x01Game = gameController.initX01Game(type, legsNumber, setsNumber, users, doubleIn, doubleOut, x01,
randomOrder, startingPoint);
JSONObject x01Json = gameController.transfromGameToJson(x01Game);
session.setAttribute("x01Game", x01Game);
request.setAttribute("x01Json", x01Json);
request.getRequestDispatcher("/darts/x01game.jsp").forward(request, response);
the method
public JSONObject transfromGameToJson(X01Game x01Game) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("x01Game.json"), x01Game);
JSONObject object = new JSONObject(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(x01Game));
return object;
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
If i delete this line from my method, it's working:
mapper.writeValue(new File("x01Game.json"), x01Game);

Server returns HTML instead of expected JSON response

The server is returning html code with JavaScript instead of returning a straight JSON response to my android application.
I have set the POST header Content-type as JSON, following is the code for parsing
public JSONObject getJSONFromUrl(String url,List params ) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-Type","application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
But the Log.e("JSON",json) is printing the following :-
E/JSON: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("61752b71ddbf41dbe3e72a15586b68db");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://recipebook.epizy.com/RecipeBook/?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
So it's obviously unable to convert that into a JSONObject.
The JavaScript option on my default browser is enabled.
Because of the object being null, I'm facing NullPointerExceptions as well.
But they will probably vanish once I get the proper JSON response.
What am I doing wrong here?
Check out your URL, it may be wrong. If the server is returning true HTML, it may not be a bug but simply a wrong call.

Export all ElasticSearch data to JSON file

I need t export all data in the ElasticSearch and reindex all those data.
The export Java code as follows.
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
String scrollid = response.getScrollId();
try {
//把导出的结果以JSON的格式写到文件里
BufferedWriter out = new BufferedWriter(new FileWriter("es", true));
while (true) {
SearchResponse response2 = client.prepareSearchScroll(scrollid)
.setScroll(new TimeValue(1000000))
.execute().actionGet();
SearchHits searchHit = response2.getHits();
//再次查询不到数据时跳出循环
if (searchHit.getHits().length == 0) {
break;
}
System.out.println("查询数量 :" + searchHit.getHits().length);
for (int i = 0; i < searchHit.getHits().length; i++) {
String json = searchHit.getHits()[i].getSourceAsString();
out.write(json);
out.write("\r\n");
}
}
System.out.println("查询结束");
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The numbers of documents is about 140W. Use this java code 60W documents can be exported and throw an exception.
远程主机强迫关闭了一个现有的连接
You have to use the scrollid from the previous response for your next request.
See https://www.elastic.co/guide/en/elasticsearch/reference/1.7/search-request-scroll.html#scroll-scan for more details
Perhaps you can try something like this instead?
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
int sequence = 0;
do
{
response = client.prepareSearchScroll(response.getScrollId())
.setScroll(new TimeValue(600000))
.execute().actionGet();
if (response.getHits().getHits().length > 0)
{
try
{
final BufferedWriter out = new BufferedWriter(new FileWriter("es-" + (++sequence) , true));
for (final SearchHit hit : response.getHits().getHits())
{
out.write(hit.getSourceAsString());
out.write("\r\n");
}
out.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
while (response.getHits().hits().length > 0);

Json Parse Failed- javafx

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help