PHP Server not connecting using JSON objects - java

I am not able to retrieve the data from the server. I am not sure where i have gone wrong in the code..When i run the application, the data from the server is not displayed on the emulator.. The code is given below
private void postData1(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxxxx.co.uk/NottTest/post.php");
JSONObject json = new JSONObject();
try {
// JSON data:
try {
json.put("name", "Fahmi Rahman");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json.put("position", "sysdev");
JSONArray postjson = new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
tv.setText("Hiii");
// for JSON:
if (response != null)
{
Log.i("Json","respose");
System.out.print("loooooooooool");
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
else{
tv.setText("no respose");
Log.i("Noting","happended");
}
//tv.setText(text);
} catch (ClientProtocolException e) {
Log.i("Error","Prtocol");
} catch (IOException e) {
Log.i("Error","IO");
} catch (JSONException e) {
Log.i("Error","JOSON");
}
}

i think the error is in
try {
json.put("name", "Fahmi Rahman");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json.put("position", "sysdev");
JSONArray postjson = new JSONArray();

Related

Not getting response of a webservice in android code

I am working on an application in that i have developed ios code for making a webservice call and it is giving me response successfully,The same webservice call when i am trying to call in android it is not working it is not giving me response,I am posting my both code,Can anybody help me to figure it?
ios code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#",k_SERVER_BASE_ADDRESS,service_name]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:[NSString stringWithFormat:#"%#",k_CONTENT_TYPE] forHTTPHeaderField:#"Content-Type"];
// 3
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_USER_NAME] forKey:#"APIUserName"];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_PASSWORD] forKey:#"Password"];
NSLog(#"%#",dictionary);
NSError *error = nil;
NSData *data_prm = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
NSLog(#"%#",[[NSString alloc] initWithData:data_prm encoding:NSUTF8StringEncoding]);
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data_prm completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here..
NSLog(#"this is data : %#",data);
Android Code
public class GETCONTESTANTS extends AsyncTask<Void, Void, Void> {
StringEntity se;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
// stateList.clear();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants");
String json = "";
try {
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jsonObject.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
se = new StringEntity(json);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
In above codes "iOS code" is working fine and "android code" is not working. Can anyone please help me?
try this snippet of code may be helpful
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
String url="http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
JSONObject jo = null;
jo = new JSONObject();
try {
jo.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jo.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject job=new JSONObject();
try {
job.accumulate("aloha", jo);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("url", job.toString());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
try {
httppost.setEntity(new StringEntity(job.toString(), "UTF- 8"));
// httppost.toString();
// Log.e("url", httppost.toString());
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
Log.e("url", json);
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}

Using JsonReader to read json url

I'm trying to read json url using JsonReader!. Once I call reader.beginArray(), I get:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING.
This is the json url :
http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631
#Override
protected String doInBackground(String... urls) {
String result = "";
String url="http://www.metlink.org.nz/stop/nearbystopdata?lat=-41.278407655948&lng=174.77938892631";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse response = httpclient.execute(httppost);
InputStream in=response.getEntity().getContent();
JsonReader reader ;
reader= new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
try {
listData=(ArrayList<DivanData>) readMessagesArray(reader);
}
finally {
reader.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public ArrayList<DivanData> readMessagesArray(JsonReader reader) throws IOException {
ArrayList<DivanData> messages = new ArrayList();
try {
reader.beginArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
reader.endArray();
return messages;
}
What am I doing wrong?
Since you have html with content why not try to fetch json as a string from the html using jsoup (http://jsoup.org/). It's really simple and requires less code:
Document d;
String url="your_url";
d = Jsoup.connect(url).get();
Element p = d.select("body p").first(); // fetch from p tag content
String jsonString = p.text();

how to post json objects to webservices like url

I want to pass JSON objects to web services like this
firstname=jhon&lastname=mic&mail=jhon#gmail.com&sex=M&hometown=blablabla
how can I pass,any one please help me.Am trying like this
JSONObject json = new JSONObject();
json.put("firstname", firstname);
json.put("lastname", laststname);
json.put("mail", mail);
json.put("sex", sex);
json.put("hometown", hometown)
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null)
{
InputStream instream=entity.getContent();
String result=convertStreamToString(instream);
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
But this code not posted the right value to webservice,Is there any wrong please help me ,
Thank you:)
StringBuilder bu = new StringBuilder();
for(int i = 0; i<json.names().length(); i++){
bu.append("&");
try {
bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bu.toString();//give you parameters

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Java / HTML : Submitting multi-line text through HTTP GET

The method I am using to get a page's content after performing a GET request is as follows:
public static String getURLContent(String URL) {
BufferedReader in = null;
String page = "";
try {
HttpClient client = getNewHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://localhost/"+URL.replace(" ", "%20")));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return page;
When I submit text from a multi-line textbox, an example URL would be:
staff_chat.php?action=send&staff_no=null&toStaff=123456&subject=RE:
test subject&message=----Previous message from: Stefan Dunn ----
to test
The new lines seem to prevent my code from setting the URI, it just skips and goes to the "return page" line.
How can I submit multi-line text through by GET?
Many thanks.

Categories

Resources