json post请求java不向服务器发送数据

时间:2014-10-12 02:43:13

标签: java php android json

我尝试创建一个对所有json请求都是唯一的类,并尝试将json请求从它发送到服务器。它只需要请求url和json StringEntity。请求发送,但问题是,当我尝试从服务器访问数据时,无法找到该帖子数据。

JSONClinet.java

package info.itranfuzz.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class JSONClient {

    private final HttpClient httpClient;
    private HttpPost httpPost;
    private HttpResponse httpResponse;

    public JSONClient() {
        httpClient = new DefaultHttpClient();
    }

    public String doPost(String url, StringEntity se) {

        InputStream inputStream = null;
        String result = "";

        httpPost = new HttpPost(url);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        httpPost.setEntity(se);
        try {
            httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

}

服务器accss代码在这里。 有电子邮件和lat和lng发送到服务器。

<?php

//set content type to json
        header('Content-type: application/json');

        $email = $this->input->post("email");
        $lat = $this->input->post('lat');
        $lng = $this->input->post('lng');

        $status = array("STATUS"=>"false");
        if($this->donor->updateLocationByEmail($email,$lat,$lng)){
            $status = array("STATUS"=>"true");
        }
        array_push($status, array("email"=>$email,"lat"=>$lat,"lng"=>$lng));
        echo json_encode($status);

?>

我的调用方法是这个

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        JSONClient jClient = new JSONClient();

        Location loc = new Location(LocationService.this);
        LatLng p = loc.getLocation();

        if (p != null) {
            String json = "";

            try {
                JSONObject jsonObject = new JSONObject();
                // jsonObject.accumulate("email", WebLoad.STORE.getEmail());
                jsonObject.put("email", "b@gmail.com");
                jsonObject.put("lat", p.getLat());
                jsonObject.put("lng", p.getLng());

                json = jsonObject.toString();

                System.out.println(jClient.doPost(WebLoad.ROOTURL
                        + "/donor_controller/updatelocation", new StringEntity(
                        json)));

            } catch (JSONException e) {
                System.out.println("Json exception occur");
            } catch (UnsupportedEncodingException e) {
                System.out.println("Unsupported ecodding exception occur");
            }

        }
        return super.onStartCommand(intent, flags, startId);
    }

2 个答案:

答案 0 :(得分:1)

//import packages


public class DBConnection {

static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";

// This is a constructor of this class
public DBConnection() {

}

/*
 * function get jsonObject from URL by making HTTP POST or GET method.
 */

public JSONObject createHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request

    try {
        // check for request method
        if (method == "POST") {
            // request method is POST and making default client.
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (ClientProtocolException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.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.w("Error" ,"My Error" + json);
    } catch (Exception ex) {
        Log.e("Buffer Error", "Error converting result " + ex.toString());
    }

    // try to parse the string to a JOSN object
    try {

        Log.w("sub",json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return new object
    return jsonObject;

}

}

请你尝试这种方式提出请求。

答案 1 :(得分:0)

$email = $this->input->$_POST('email')

使用这种方式任何尝试。将帖子更改为$ _POST [&#39;变量名称&#39;]。正如我告诉你的那样,你写信给服务器端的PHP。在PHP get和post方法中,我们访问$ _GET和$ _POST。