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

标签 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;

    }

}

服务器访问代码在这里。 有电子邮件以及纬度和经度发送到服务器。

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

最佳答案

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

}

}

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

关于java - json post请求java不发送数据到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26321331/

相关文章:

java - 在 Box2D 对象上分配纹理

java - 在Java中使用正则表达式进行部分搜索

php - while循环if语句NULL问题

php - 在 Eclipse 中运行 PHP Zend 测试

USBAccessory 的 Android list

android - 如何避免回调后 OkHttp Dispatcher 中出现致命异常

android - 从 Thread.UncaughtExceptionHandler 启动服务?

java - 将文件加载为 InputStream 的不同方式

java dx 实用程序 : UNEXPECTED TOP-LEVEL ERROR java. lang.ExceptionInInitializerError

php - VMware Workstation 上虚拟机之间的网络